Longest Run of Ones After K Flips
Solve this Problemnums and an integer k — you may flip up to k zeros to ones. Return the length of the longest contiguous run of 1s you can achieve.
Re-checking every possible starting point from scratch is wasteful: as the window slides forward, most of its elements stay the same. A variable-size sliding windowVariable-Size Sliding WindowA window whose right edge always advances, but whose left edge only advances when a constraint is violated — so the window grows and shrinks in response to what it currently holds, rather than staying a fixed size. tracks how many 0s the current window is "spending" as flips; whenever that count exceeds k, the left edge shrinks just enough to bring it back within budget, and every position is visited by each pointer at most once.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ nums.length ≤ 10⁵ - ◆
nums[i] is either 0 or 1 - ◆
0 ≤ k ≤ nums.length
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public int longestRunOfOnesAfterKFlips(int[] nums, int k) { |
| 3 | int left = 0, zeros = 0, maxLen = 0; |
| 4 | for (int right = 0; right < nums.length; right++) { |
| 5 | if (nums[right] == 0) zeros++; |
| 6 | while (zeros > k) { |
| 7 | if (nums[left] == 0) zeros--; |
| 8 | left++; |
| 9 | } |
| 10 | maxLen = Math.max(maxLen, right - left + 1); |
| 11 | } |
| 12 | return maxLen; |
| 13 | } |
| 14 | } |
| 15 |
000Start left at 0, zeros used at 0, and maxLen at 0. Grow the window from the right, one index at a time.
Approach & Solutions
Brute Force
BruteFor every possible start index, expand as far right as possible while counting how many 0s have been used as flips. Stop expanding the moment a further flip would exceed k, and track the longest reach seen. Correct, but every start index re-walks ground the one before it already covered.
O(n²)O(1)1class Solution {
2 public int longestRunOfOnesAfterKFlips(int[] nums, int k) {
3 int maxLen = 0;
4 for (int i = 0; i < nums.length; i++) {
5 int zeros = 0;
6 int j = i;
7 while (j < nums.length) {
8 if (nums[j] == 0) zeros++;
9 if (zeros > k) break;
10 j++;
11 }
12 maxLen = Math.max(maxLen, j - i);
13 }
14 return maxLen;
15 }
16}Optimal — Sliding Window
OptimalGrow a window from the right, counting the 0s inside it. Whenever that count goes over k, shrink from the left until it's back within budget — every index still only ever moves forward, so the whole scan is a single O(n) pass. The window's length after each step is a candidate answer.
O(n)O(1)1class Solution {
2 public int longestRunOfOnesAfterKFlips(int[] nums, int k) {
3 int left = 0, zeros = 0, maxLen = 0;
4 for (int right = 0; right < nums.length; right++) {
5 if (nums[right] == 0) zeros++;
6 while (zeros > k) {
7 if (nums[left] == 0) zeros--;
8 left++;
9 }
10 maxLen = Math.max(maxLen, right - left + 1);
11 }
12 return maxLen;
13 }
14}