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.
1public class MaxConsecutiveOnes {
2 public static int findMaxConsecutiveOnes(int[] nums) {
3 int maxCount = 0, currentCount = 0;
4 for (int num : nums) {
5 if (num == 1) {
6 currentCount++;
7 maxCount = Math.max(maxCount, currentCount);
8 } else {
9 currentCount = 0;
10 }
11 }
12 return maxCount;
13 }
14
15 public static void main(String[] args) {
16 int[] nums = {1, 1, 0, 1, 1, 1};
17 System.out.println("The maximum number of consecutive 1s is: " + findMaxConsecutiveOnes(nums));
18 }
19}
20
This Java program employs a for-each loop to iterate over the array. The principles of counting and resetting are maintained as described.
This approach uses a variation of the sliding window technique. The idea is to maintain a window of the current sequence of 1s and adjust the window whenever a 0 is encountered.
Time Complexity: O(n)
Space Complexity: O(1)
1#include <iostream>
2#include <vector>
using namespace std;
int findMaxConsecutiveOnes(vector<int>& nums) {
int left = 0, right = 0, maxCount = 0;
while (right < nums.size()) {
if (nums[right] == 0) {
left = right + 1;
}
maxCount = max(maxCount, right - left + 1);
++right;
}
return maxCount;
}
int main() {
vector<int> nums = {1, 0, 1, 1, 0, 1};
cout << "The maximum number of consecutive 1s is: " << findMaxConsecutiveOnes(nums) << endl;
return 0;
}
This C++ solution expands on the sliding window technique, ensuring that left
is moved to keep the window focusing on 1s by adjusting based on zeroes found at right
.