EasyNo. 0485
Max Consecutive Ones — LeetCode 485 Python Solution
- Topics
- Array
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example
- 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.
Python solution
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
ans = cnt = 0
for x in nums:
if x:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ansComplexity
- Time
- O(n)where n is the length of the array
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1004 | Max Consecutive Ones III | Medium |
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
Frequently asked questions
- How hard is LeetCode 485. Max Consecutive Ones?
LeetCode 485. Max Consecutive Ones is rated Easy on LeetCode.
- What is the time complexity of LeetCode 485. Max Consecutive Ones?
The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 485. Max Consecutive Ones?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 485. Max Consecutive Ones cover?
LeetCode 485. Max Consecutive Ones is tagged Array on LeetCode.