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 1s and updating the maximum streak whenever we encounter a 0 or reach the end of the array.
Approach
- Initialization: We use two variables,
current_countto keep track of the current streak of consecutive 1s andmax_countto store the maximum streak found so far. Both are initialized to 0. - Iterate through the array:
- If the current element is 1, increment
current_count. - If the current element is 0, update
max_countifcurrent_countis greater thanmax_count, then resetcurrent_countto 0.
- If the current element is 1, increment
- Final Check: After the loop ends, we need to check the
current_countone last time (since the longest streak might end at the last element of the array). - Return Result: The value of
max_countis the answer.
Solution Code
def findMaxConsecutiveOnes(nums):
current_count = 0
max_count = 0
for num in nums:
if num == 1:
current_count += 1
else:
if current_count > max_count:
max_count = current_count
current_count = 0
# Check the last streak in case it ends with 1s
if current_count > max_count:
max_count = current_count
return max_count
Explanation
- Initialization: We start with both
current_countandmax_countset to 0 because there are no 1s initially. - Loop Through Array: For each element:
- When we see a 1, we increase the current streak.
- When we see a 0, we compare the current streak to the maximum streak and update the maximum if needed, then reset the current streak to 0.
- Final Check: This handles the case where the array ends with a streak of 1s (since we wouldn't have updated
max_countin the loop). - Efficiency: The algorithm runs in O(n) time complexity where n is the length of the array, as we traverse the array once. The space complexity is O(1) since we only use a few variables.
This approach efficiently finds the maximum number of consecutive 1s with optimal time and space complexity. It handles all edge cases, including arrays with no 1s, all 1s, and mixed 0s and 1s.


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