LeetCode 1004 Maximum number of consecutive 1s III HERODING's LeetCode road

Given an array A consisting of several 0s and 1, we can change up to K values ​​from 0 to 1.

Returns the length of the longest (contiguous) sub-array containing only 1.

Example 1:

Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1 ,1,1,1,1] The
numbers in bold are flipped from 0 to 1, and the longest sub-array length is 6.

Example 2:

Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bold numbers are flipped from 0 to 1, The longest sub-array length is 10.

prompt:

1 <= A.length <= 20000
0 <= K <= A.length
A[i] 为 0 或 1 

Source: LeetCode
Link: https://leetcode-cn.com/problems/max-consecutive-ones-iii The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving idea:
This is a classic sliding window problem. As long as the number of zeros in the window does not exceed K within the window range, then the length of the window meets the condition of a continuous sub-array, and what we are looking for is the longest The sub-array that meets this condition, so first we define the maximum length, the left side of the window, the right side of the window, when traversing the array, if you encounter 0, then K–, that is, one opportunity to change 0 to 1 is used, this time If the number of 0s in the window is more than K, keep moving the left side of the window until the number of 0s in the window is less than or equal to K, and finally update the maximum length. code show as below:

class Solution {
    
    
public:
    int longestOnes(vector<int>& A, int K) {
    
    
        // 定义最大长度,窗口的左边,窗口的右边
        int max_len = K;
        int left = 0;
        int right = 0;
        while(right < A.size()) {
    
    
            // 如果遇到的是0
            if(A[right] == 0) {
    
    
                K --;
            }
            // 更新窗口左边位置
            while(K < 0) {
    
    
                K = K + 1 - A[left];
                left ++;
            }
            // 更新最大长度
            max_len = max(max_len, right - left + 1);
            // 窗口右移
            right ++;
        }
        return max_len;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/max-consecutive-ones-iii/solution/ji-bai-shuang-95zui-xiang-xi-csi-lu-by-h-sufl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

Guess you like

Origin blog.csdn.net/HERODING23/article/details/113855874