Max Consecutive Ones — LeetCode 485 Python Solution
EasyArray
- Problem
- #485
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
Related problems
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.