Problem
Given a binary arraynums, return the maximum number of consecutive 1’s in the array.
Examples
Constraints
1 <= nums.length <= 10^5nums[i]is either0or1.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 485 with 12 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 485 # by problem number
lcpy gen -s max_consecutive_ones # by problem name
nums, return the maximum number of consecutive 1’s in the array.
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Input: nums = [1,0,1,1,0,1]
Output: 2
1 <= nums.length <= 10^5nums[i] is either 0 or 1.class Solution:
# Time: O(n)
# Space: O(1)
def find_max_consecutive_ones(self, nums: list[int]) -> int:
best = 0
current = 0
for num in nums:
if num == 1:
current += 1
best = max(best, current)
else:
current = 0
return best
| Time | Space |
|---|---|
| O(n) | O(1) |