[Algorithm Topic Breakthrough] Double Pointers - Maximum Number of Consecutive 1s III (11)

Table of contents

1. Question analysis

2. Algorithm principle

3. Code writing

Write at the end:


1. Question analysis

Question link: 1004. Maximum number of consecutive 1's III - Leetcode

This question is not difficult to understand. In fact, it is to find the longest continuous subarray of 1.

However, it supports an operation, which is to flip k 0s into 1s.

Once this condition came out, the difficulty of this question increased, and the situation became more complicated. 

2. Algorithm principle

Then we can think about how to abstract a rule:

Transform this problem into: find the longest subarray with no more than k 0s,

If you use violent enumeration, the idea is relatively simple.

Based on brute force enumeration, we can use sliding windows to optimize this problem,

In fact, the most difficult step: we have already finished the conversion problem. We only need to design the sliding window based on this idea.

We maintain a window,

When the number of 0s is less than 2, the window is continuously expanded,

When the number of 0s is equal to 2, we record the longest subarray,

When the number of 0s is greater than 2, we reduce the window until the number of 0s is less than or equal to 2

Let’s look at the code:

3. Code writing

class Solution {
public:
    int longestOnes(vector<int>& nums, int k) {
        unordered_map<int, int> win;
        int len = 0, left = 0, right = 0;
        while(right < nums.size()) {
            len = max(len, right - left);
            win[nums[right++]]++;
            while(left < nums.size() && win[0] > k) {
                win[nums[left++]]--;
            }
        }
        len = max(len, right - left);
        return len;
    }
};

Write at the end:

That’s the content of this article, thank you for reading.

If you feel you have gained something, you can give the blogger a like .

If there are omissions or errors in the content of the article, please send a private message to the blogger or point it out in the comment area~

Guess you like

Origin blog.csdn.net/Locky136/article/details/131707287