↓Skip to main content
  1. LeetCode/

LeetCode 485: Max Consecutive Ones

·1 min· ·
LeetCode Easy Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Accepted ×4

Approach
#

Like LC 674, walk the runs (Array Template 1): add one on a 1, reset on a 0, and update the maximum each step.

My Solution
#

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        best = cur = 0
        for x in nums:
            cur = cur + 1 if x == 1 else 0
            best = max(best, cur)
        return best

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Update the maximum every step so the last run is not missed.

Interview Explanation
#

I scan once, adding one on each 1 and resetting on each 0, updating the maximum every step. Time O(n), space O(1).

Related

LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 118: Pascal's Triangle
·1 min
LeetCode Easy Array Dynamic-Programming
LeetCode 118 note: each row starts and ends with 1, and every inner cell is the sum of the two cells above it
LeetCode 136: Single Number
·1 min
LeetCode Easy Array Bit-Manipulation
LeetCode 136 note: x ^ x = 0 and x ^ 0 = x, so XOR everything; pairs cancel and the single number remains
LeetCode 414: Third Maximum Number
·1 min
LeetCode Easy Array Sorting
LeetCode 414 note: track the three largest distinct values, skipping repeats, and return the maximum if fewer than three distinct values exist
LeetCode 448: Find All Numbers Disappeared in an Array
·1 min
LeetCode Easy Array Hash-Table
LeetCode 448 note: use the array itself as the hash table, marking nums[x - 1] negative for each x; positions still positive are the missing numbers