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.
1function findMaxConsecutiveOnes(nums) {
2 let maxCount = 0;
3 let currentCount = 0;
4 for(let num of 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
15let nums = [1, 1, 0, 1, 1, 1];
16console.log(`The maximum number of consecutive 1s is: ${findMaxConsecutiveOnes(nums)}`);
This JavaScript function uses a for...of
loop to iterate through the array. It keeps track of the current and maximum number of consecutive 1s.
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)
1using System;
2
public class MaxConsecutiveOnes {
public static int FindMaxConsecutiveOnes(int[] nums) {
int left = 0, maxCount = 0;
for (int right = 0; right < nums.Length; right++) {
if (nums[right] == 0) {
left = right + 1;
}
maxCount = Math.Max(maxCount, right - left + 1);
}
return maxCount;
}
public static void Main() {
int[] nums = {1, 0, 1, 1, 0, 1};
Console.WriteLine("The maximum number of consecutive 1s is: " + FindMaxConsecutiveOnes(nums));
}
}
This C# solution applies the sliding window approach by dynamically adjusting the potential sequence boundaries with respect to encounters with zeros.