NeetCode #37LC-485EasyArrays & Hashing
← Back to All Problems

#37 · #485 · Max Consecutive Ones(最大连续 1 的个数)

📌 Problem Statement & Constraints

Given a binary array nums, return the maximum number of consecutive 1s in the array. Constraints: 1 <= nums.length <= 10^5, nums[i] is 0 or 1.

💡 Core Algorithmic Approaches

  1. Keep a running counter of the current run of ones and a global best.
  2. On a 1, increment the counter and update the best.
  3. On a 0, reset the counter to zero.
  4. This is the template for all maximum-consecutive-run problems, including the sliding-window variants that allow flipping a limited number of zeros.

💻 Benchmark Python3 Implementation

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

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): two counters.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting to reset on 0: the counter would accumulate across runs and overcount.
  • Using a sliding window: unnecessary here since the array is binary and the constraint is exact -- a simple counter suffices.
  • Initialising best to 1: an all-zero array must return 0.