Sliding Window· 25 min
Max Consecutive Ones III
LeetCode #1004 · Medium · Interactive step-by-step visualization
Setup
Example input
nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2Step 1 / 50
Current step
1 / 50Enter index 0. The right boundary expands to inspect one new value. 1 enters the window.
Step log
nums, k = 2 flips allowed
CURRENT WINDOW
1Enter
01
11
20
30
40
51
61
71
81
90
10Current dotted windowSaved best rangeEnter index 0
zeroes
0
best
0
Active cursor
Comparing
Best or completed
Leaving or removed
max-consecutive-ones-iii.java
1public int longestOnes(int[] nums, int k) {2 int left = 0, zeroes = 0, best = 0;3 for (int right = 0; right < nums.length; right++) {4 if (nums[right] == 0) zeroes++;5 while (zeroes > k) {6 if (nums[left++] == 0) zeroes--;7 }8 best = Math.max(best, right - left + 1);9 }10 return best;11}● Java
Time
O(n)
Space
O(1)
Pattern
sliding window
Frames
50
