To solve this problem, we need to find the maximum number of consecutive 1s in a binary array. The approach involves tracking the current streak of consecutive 1s and updating the maximum streak whenever the current streak exceeds the previous maximum.
Approach
-
Initialization:
current_streak: To keep track of the length of the current consecutive 1s.max_streak: To store the maximum length of consecutive 1s encountered so far.
-
Iterate through the array:
- For each element in the array:
- If the element is 1, increment
current_streakand updatemax_streakifcurrent_streakis greater thanmax_streak. - If the element is 0, reset
current_streakto 0 (since the consecutive streak of 1s breaks here).
- If the element is 1, increment
- For each element in the array:
-
Return the result: After processing all elements,
max_streakwill hold the desired value.
Solution Code
def findMaxConsecutiveOnes(nums):
current_streak = 0
max_streak = 0
for num in nums:
if num == 1:
current_streak += 1
if current_streak > max_streak:
max_streak = current_streak
else:
current_streak = 0
return max_streak
Explanation
- Time Complexity: O(n) where n is the length of the array. We traverse the array once, making this solution efficient.
- Space Complexity: O(1) since we only use a few variables to track the streaks, no additional data structures are needed.
This approach ensures that we efficiently find the maximum consecutive 1s with optimal time and space complexity. It handles all edge cases, including arrays with all 0s, all 1s, or a mix of both. For example:
- Input: [1,1,0,1,1,1] → Output:3 (the last three 1s)
- Input: [0,0,0] → Output:0
- Input: [1] → Output:1
This solution is straightforward and effective for the given problem.


作者声明:本文包含人工智能生成内容。