Variable window
Time O(n) Space O(1)Count zeros in the window; shrink from the left while zeros > k; track the best length.
nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2state(vars)
Step 1/5Growing from the left, the window [0..4] holds two zeros, exactly k. Best so far: 5.
class Solution {
public int longestOnes(int[] nums, int k) {
int best = 0, zeros = 0;
for (int l = 0, r = 0; r < nums.length; r++) {
if (nums[r] == 0) zeros++;
while (zeros > k) if (nums[l++] == 0) zeros--;
best = Math.max(best, r - l + 1);
}
return best;
}
}Verdict: Each index enters and leaves once.