【题解】【直方图】【Leetcode】Trapping Rain Water

时间:2023-03-08 15:40:59

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

【题解】【直方图】【Leetcode】Trapping Rain Water

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

思路:

O(n) solution. for each bar, find the max height bar on the left and right. then for this bar it can hold min(max_left, max_right) - height

对于任何一个坐标,检查其左右的最大坐标,然后相减就是容积。所以, 
1. 从左往右扫描一遍,对于每一个坐标,求取左边最大值。 
2. 从右往左扫描一遍,对于每一个坐标,求最大右值。

直方图的题还有Container With Most WaterLargest Rectangle in Histogram,还可以看看Maximal Rectangle,都很有意思

代码:

 int trap(int A[], int n) {
if(n < )
return ; vector<int> maxRs(n);
int maxR = ;
for(int i = ; i < n; i++){
if(A[i] > maxR)
maxR = A[i];
maxRs[i] = maxR;
} int totalV = ;
int maxL = ;
for(int i = n-; i >= ; i--){
if(A[i] > maxL)
maxL = A[i];
totalV += min(maxL, maxRs[i]) - A[i];
}
return totalV;
}