Given a binary array nums
, return the maximum number of consecutive 1
s in the array.
Clarifying Questions
- Constraints on Length of Array: What is the maximum length of the array?
- The problem does not explicitly state this, but we can assume the array length can be quite large (up to (10^5) elements).
- Array Contents: Can the array contain negative numbers or numbers other than 0 or 1?
- No, the array is strictly binary, containing only 0s and 1s.
- Empty Array: What should be the output if the array is empty?
- If the array is empty, there are no consecutive ones, so the output should be 0.
Strategy
- Initialize Counters: We’ll use two variables: one to keep track of the current streak of consecutive 1s and another to store the maximum streak found.
- Iterate Through Array: We’ll loop through the array. For each element:
- If it’s 1, increment the current streak counter.
- If it’s 0, update the maximum streak if the current streak is greater and reset the current streak counter.
- Final Check: After the loop, check the current streak one last time to update the maximum streak if needed.
- Result: The maximum streak counter will hold our result.
Code
def findMaxConsecutiveOnes(nums):
max_consecutive = 0
current_streak = 0
for num in nums:
if num == 1:
current_streak += 1
max_consecutive = max(max_consecutive, current_streak)
else:
current_streak = 0
return max_consecutive
Time Complexity
The time complexity of this approach is ( O(n) ), where ( n ) is the length of the array. This is because we iterate through the array once, performing constant-time operations for each element.
The space complexity is ( O(1) ) since we are using a fixed amount of extra space regardless of the input size.
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?