Colliding double pointers (2) The problem of receiving rainwater

The rainwater problem_Niuke Questions_Niuke

describe

Given an integer array arr, all the values ​​in it are known to be non-negative, consider this array as a column height map, and calculate how much rainwater can be received by the columns arranged in this way after it rains. (The height of the area outside the array is regarded as 0)

 Using the idea of ​​collision double pointers, let left and right perform collision traversal from the left and right ends respectively

Each time maintains a middle two maximum value, left area max and right area max, when Lmax is less than Rmax, calculate the rainwater of the current column from the left side, and subtract the current height from Lmax of the current part to get the rainwater of the current column quantity.

 

Ideas:

We all know the short board of the bucket, and the shortest board controls the water volume of the bucket. This question is also similar. We can regard the whole picture as a bucket. The two sides are the plates of the bucket, and the lower part in the middle is the bottom of the bucket. The shorter side controls the maximum water volume of the bucket. But there may be a higher side in the bucket, such as the fourth column in the above picture, which is higher than the side of the bucket. In this case, does it divide a bucket into two buckets, and the side in the middle is The sides of the two buckets.

With this idea, it is easy to solve this problem, because our bucket here has two sides, so we can consider using colliding double pointers to lean towards the middle.

specific methods:

  • step 1: special case of checking if the array is empty
  • Step 2: Prepare double pointers, pointing to the first and last elements of the array respectively, representing the first two boundaries
  • Step 3: The pointer traverses to the middle, and when it encounters a lower column, it is the bottom. Subtracting the bottom from the shorter boundary is the water intake of this column. When it encounters a higher column, it is the new boundary, and the size of the boundary is updated.

class Solution {
public:
    long long maxWater(vector<int>& arr) {
        // write code here
        if(arr.empty())return 0;
        long long res = 0;
        int left = 0, right = arr.size()-1;
        int Lmax = 0, Rmax = 0;    // 俩个区间的max
        while(left < right)
        {
            Lmax = max(Lmax, arr[left]);    // 维护左右区间的max
            Rmax = max(Rmax, arr[right]);
            if(Lmax < Rmax)        
                res += Lmax - arr[left++];    // 总是计算小的一方的雨水量
            else
                res += Rmax - arr[right--];
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/weixin_66151870/article/details/129094341