Sponsored
Sponsored
This approach involves iterating through the array and counting sequences of 1s. If a 0 is encountered, the count is reset to 0. We keep track of the maximum count during the iteration.
Time Complexity: O(n), where n is the number of elements in the array, as we make a single pass.
Space Complexity: O(1) since no extra space proportional to input size is used.
1#include <iostream>
2#include <vector>
3
4int findMaxConsecutiveOnes(std::vector<int>& nums) {
5 int maxCount = 0, currentCount = 0;
6 for(int num : nums) {
7 if(num == 1) {
8 currentCount++;
9 maxCount = std::max(maxCount, currentCount);
10 } else {
11 currentCount = 0;
12 }
13 }
14 return maxCount;
15}
16
17int main() {
18 std::vector<int> nums = {1, 1, 0, 1, 1, 1};
19 std::cout << "The maximum number of consecutive 1s is: " << findMaxConsecutiveOnes(nums) << std::endl;
20 return 0;
21}
This C++ solution uses a for-each loop for cleanly iterating over each element in the vector. The logic remains similar: incrementing the count for each 1 and resetting on encountering a 0.
In this version, two pointers left
and right
maintain the window of consecutive 1s. When a 0 is found, left
is moved to right + 1
, effectively 'skipping' the segments with 0s, adjusting the window accordingly.