Leetcode 1004. Max Consecutive Ones III 滑动窗口经典题

  1. Max Consecutive Ones III
    Medium
    Given a binary array nums and an integer k, return the maximum number of consecutive 1’s in the array if you can flip at most k 0’s.

Example 1:

Input: nums = [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]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:

Input: nums = [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]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.

Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.
0 <= k <= nums.length

解法1:直接套用滑动窗口模板
注意:为什么这题可以用滑动窗口,而Leetcode 1124. Longest Well-Performing Interval 这题就不能用呢?
因为这题的滑动窗口满足单调性,即右指针移动直到当前窗口不合格时(即flipCount>k),再移动右指针,当前窗口肯定还是不合格(因为flipCount还是>k)。而Leetcode1124里面,当我们移动右指针直到当前窗口不合格时(即>8小时的天数小于等于<=8小时的天数),再移动右值时,当前窗口可能又合格了,因为又加入了更多的>8小时的天数。
另外,如果不能用滑动窗口,那我们还是可以用前缀和数组+hashmap来处理。

class Solution {
    
    
public:
    int longestOnes(vector<int>& nums, int k) {
    
    
        int n = nums.size();
        int left = 0, right = 0;
        int res = 0, flipCount = 0;
        while (right < n) {
    
    
            if (nums[right] == 0) flipCount++;
            right++;
            while (left < right && flipCount > k) {
    
      //注意left<right,不是left<=right。flipCount>k不是>=,因为=是合法窗口,不需要收缩左边界。
                if (nums[left] == 0) flipCount--;
                left++;
            }
            res = max(res, right - left);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/132798418