Max Consecutive Ones — LeetCode 485 Python Solution

EasyArray
Problem
#485
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview