1004. Max Consecutive Ones III
count zero
T: O(n)
S: O(1)
class Solution {
    public int longestOnes(int[] nums, int k) {
        int zeroCount = 0;
        int left = 0;
        int right = 0;
        int result = 0;
        
        while (right < nums.length) {
            if (nums[right] == 0) {
                zeroCount++;
            }
            right++;
            if (zeroCount <= k) {
                result = Math.max(result, right - left);
            }
            while (zeroCount > k) {
                if (nums[left] == 0) {
                    zeroCount--;
                }
                left++;
            }
        }
        return result;
    }
}
/*
when match or lower k zero -> get ans, 
when over k zero, start to shrink left
[1,1,1,0,0,0,1,1,1,1,0]
        l
                     r
                     
[1,1,1,0,1,1,1,1,1,1,1] zerocount < k 時 or zerocount == k 時. 都要計算
*/count one
class Solution {
    public int longestOnes(int[] nums, int k) {
        int oneCount = 0;
        int left = 0;
        int right = 0;
        int result = 0;
        
        while (right < nums.length) {
            if (nums[right] == 1) {
                oneCount++;
            }
            right++;
            while (right - left - oneCount > k) {
                if (nums[left] == 1) {
                    oneCount--;
                }
                left++;
            }
            result = Math.max(result, right - left);
        }
        return result;
    }
}
/*
另一個方向思路, count one
[1,1,1,0,0,0,1,1,1,1,0]
         l
                   r
總長 - oneCount (也就是 zeroCount) <= k -> ok 的 -> 算結果
總長 - oneCount (也就是 zeroCount) > k (代表太長了, 要 shrink left)
*/Last updated
Was this helpful?