MEDIUM Sliding Window

485. Max Consecutive Ones

๐Ÿ“– Problem

Given a binary array nums, return the maximum number of consecutive 1's in the array.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขString/array indexing
  • โ€ขSet/Map frequency counting
  • โ€ขPointer movement invariants

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Sliding Window reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Sliding window to track current consecutive ones
  • โ†’ Reset count when encountering 0
  • โ†’ Track maximum count seen
  • โ†’ Time: O(n), Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขSliding window to track current consecutive ones
  • โ€ขReset count when encountering 0
  • โ€ขTrack maximum count seen

Common Pitfalls

  • โ€ขTime: O(n), Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
longestOnes([1,1,0,1,1,1]);
Expected:
3
Test Case 2
Not run
Input:
longestOnes([1,0,1,1,0,1]);
Expected:
2
Test Case 3
Not run
Input:
longestOnes([0,0,0,0]);
Expected:
0

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit