This problem can be solved by sliding window:

1. firstly the right point, j, start to move, if it meet a zero, the zeroNum++, which means, we convert one 0 to 1.

2. If we converted too many 0s to 1, we need to move left point, i, forward, until we don't have too many 0s converted.

3. We check whether the current window is larger.

    public int longestOnes(int[] nums, int k) {
        int zeroNum = 0, res =0;
        int i = 0;
        for(int j=0;j<nums.length;j++){
            if(nums[j]==0){
                zeroNum++;   //we convert one 0 to 1
            }
            if(zeroNum>k){
                if(nums[i]==0){
                    zeroNum--;  //we convert 1 to 0 again
                }
                i++;
            }
            res = Math.max(res, j-i+1);  //checker whether the current window is larger
        }
        return res;
    }

 

posted on 2022-02-03 03:03  阳光明媚的菲越  阅读(22)  评论(0编辑  收藏  举报