Sliding Window· 25 min

Max Consecutive Ones III

LeetCode #1004 · Medium · Interactive step-by-step visualization

Setup

Example inputnums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Step 1 / 50

Current step

1 / 50

Enter 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
0
1
1
1
2
0
3
0
4
0
5
1
6
1
7
1
8
1
9
0
10
Current 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