EasyNo. 0485

Max Consecutive Ones — LeetCode 485 Python Solution

Topics
Array
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

PythonSolution
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

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

Related problems

Related problems
No.ProblemDifficulty
1004Max Consecutive Ones IIIMedium
0057Insert IntervalMedium
0228Summary RangesEasy
0665Non-decreasing ArrayMedium
0674Longest Continuous Increasing SubsequenceEasy
0699Falling SquaresHard

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.

Free to download. Check it runs on your machine, then pick a plan.