I wanted to use sliding window, but it was kind of hard for me to think of a way to change the size of the window.
At first, I thought to save the index of 0 and slide the window size of k. To do that, I had to loop too many times and it didn’t worked. Finally I saw the solution, and it wasn’t straightforward to understand.
After I understood the answer, I wrote the method in my way.
class Solution {
public int longestOnes(int[] nums, int k) {
int max = 0;
int zeros = 0;
int right;
int left = 0;
for (right = 0; right < nums.length; right++) {
if (nums[right] == 0) zeros++;
if (zeros > k) {
if (nums[left] == 0) zeros--;
left++;
}
if (zeros <= k) max = Math.max(max, right - left + 1);
}
return max;
}
}