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
.
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!
这道题也是道经典题,方法是从左向右扫,求每个 index 的左边的 max;然后从右向左扫,求每个 index 的右边的 max。然后求两者之间的 min,减去自身的 value。
其实扫两遍就 okay 了,这里为了代码更为直观,所以还是扫三遍。
class Solution {
public:
int trap(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==0) return 0;
vector<int> leftMax(n,0);
vector<int> rightMax(n,0);
leftMax[0] = A[0];
rightMax[n-1] = A[n-1];
int sum = 0;
for(int i=1;i<n;i++)
{
leftMax[i] = max(leftMax[i-1],A[i]);
}
for(int i=n-2;i>=0;i--)
{
rightMax[i] = max(rightMax[i+1],A[i]);
}
for(int i=0;i<n;i++)
{
sum += min(leftMax[i],rightMax[i]) - A[i];
}
return sum;
}
};