Leetcode 485. Max Consecutive Ones
Given a binary array nums, return the maximum number of consecutive 1s in the array.
nums:
nums can be between 0 and 10^5.0 and 1?
nums is a binary array.0 since there are no 1s.1s (currentCount), and another to store the maximum count encountered so far (maxCount).1, increment the currentCount.0, compare currentCount with maxCount and update maxCount if necessary. Then, reset currentCount to zero since the sequence of consecutive 1s is broken.maxCount one last time as the longest streak might be at the end of the array.n is the length of the array nums. This is because we are performing a single pass through the array.#include <vector>
#include <algorithm> // for the std::max function
class Solution {
public:
int findMaxConsecutiveOnes(std::vector<int>& nums) {
int maxCount = 0;
int currentCount = 0;
for(int num : nums) {
if(num == 1) {
currentCount++;
} else {
maxCount = std::max(maxCount, currentCount);
currentCount = 0;
}
}
// Final comparison in case the array ends with a sequence of 1s
maxCount = std::max(maxCount, currentCount);
return maxCount;
}
};
maxCount and currentCount are initialized to 0.nums, we check if it is 1. If it is, currentCount is incremented.0, this means the sequence of consecutive 1s has ended. We then update maxCount if currentCount (the length of the recent sequence) is greater than maxCount, and reset currentCount to 0.maxCount is compared with currentCount once more, in case the array ended with a sequence of 1s.This ensures that the function correctly identifies the longest sequence of consecutive 1s in the binary array nums.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?