[Algorithm Breakthrough] Sliding window - the minimum number of operations (12) to reduce x to 0

Table of contents

1. Question analysis

2. Algorithm principle

3. Code writing

Write at the end:


1. Question analysis

 Question link: 1658. Minimum number of operations to reduce x to 0 - Leetcode

This question is not difficult to understand. In fact, it is to find the value in the array until x is reduced to 0.

What should be noted here is that the ability required to be removed by the question is the leftmost or rightmost value of the array.

Then just return the smallest operand.

It may not be easy to solve it if you look directly from both sides.

We can transform this problem into:

Find the longest intermediate subarray so that we get the smallest operand.

2. Algorithm principle

This problem can be solved using sliding windows,

The specific idea is as follows:

The sum of the arrays - x = target, this target value is the value of the middle array,

We maintain a window and constantly add values ​​into the window.

If the total value of the window < target, continue to enter the window

If == target, then record the number of operations,

If > target, the window will pop up.

Let’s look at the code:

3. Code writing

class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int left = 0, right = 0, sum = 0, len = INT_MAX, target = -x;
        for(auto e : nums) target += e;
        if(target < 0) return -1;
        int n = nums.size();
        while(right < n) {
            sum += nums[right++];
            while(left < n && sum > target) sum -= nums[left++];
            if(sum == target) len = min(len, n - (right - left));
        }
        return len == INT_MAX ? -1 : 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/131718787