Intuition
Maintain a window with at most k zeros. Expand right; when zeros exceed k, shrink left.
Explanation
Approach
- Sliding window [left, right].
- Expand right, count zeros in window.
- When zeros > k, shrink left until zeros <= k.
- Track max window size.
Complexity
- Time: O(n)
- Space: O(1)
Implementation
class Solution {
public int longestOnes(int[] nums, int k) {
int left = 0, zeros = 0, maxLen = 0;
for (int right = 0; right < nums.length; right++) {
if (nums[right] == 0) {
zeros++;
}
while (zeros > k) {
if (nums[left] == 0) {
zeros--;
}
left++;
}
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
}