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.
1def findMaxConsecutiveOnes(nums):
2 maxCount = 0
3 currentCount = 0
4 for num in nums:
5 if num == 1:
6 currentCount += 1
7 maxCount = max(maxCount, currentCount)
8 else:
9 currentCount = 0
10 return maxCount
11
12nums = [1, 1, 0, 1, 1, 1]
13print("The maximum number of consecutive 1s is:", findMaxConsecutiveOnes(nums))
This Python code iterates through the list nums
, updating counts similarly to previous implementations. It's straightforward with the use of Python's built-in max
function.
This Python solution applies the same technique using the right
index iterating over the list, dynamically adjusting the left
boundary when it hits zero.