> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/02-25-2022-1004.md).

# 02/25/2022 1004

Method:

Use sliding window. set left and right pointer, increase right pointer. If the element is 0, then decrement the k value. if k < 0, it means we  we have consumed all allowed flips and window has more than allowed zeros, thus increment left pointer by 1 to keep the window size same. If the left element is 0, then k++. finally return right - left.

Time O(N)

Space O(1)

```
            // 
```

```
class Solution {
    public int longestOnes(int[] nums, int k) {
        int left = 0, right;
        for (right = 0; right < nums.length; right++) {
            // If we included a zero in the window we reduce the value of k.
            // Since k is the maximum zeros allowed in a window.
            if (nums[right] == 0) {
                k--;
            }
            // A negative k denotes we have consumed all allowed flips and window has
            // more than allowed zeros, thus increment left pointer by 1 to keep the window size same.
            if (k < 0) {
                // If the left element to be thrown out is zero we increase k.
                k += 1 - nums[left];
                left++;
            }
        }     
        return right - left;
    }
}
```
