问题:
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!
分析:对于每一个位置来说,它能积水的多少取决于它左边最高的,和右边最高的。所以我们遍历两次,一次计算每一个位置左边最高的;一次计算每一个位置右边最高的。然后,该位置的积水量就是:max(0, min(right[i], left[i]) - A[i])。
代码:
class Solution {
public:
int trap(int A[], int n) {
int left[n];
int right[n];
int max_val = A[0];
left[0] = 0;
for (int i = 1; i < n; i ++) {
max_val = max(max_val, A[i-1]);
left[i] = max_val;
}
max_val = A[n-1];
right[n-1] = 0;
for (int i = n-2; i >= 0; i --) {
max_val = max(max_val, A[i+1]);
right[i] = max_val;
}
int result = 0;
for (int i = 0; i < n; i ++) {
result += max(0, min(right[i], left[i]) - A[i]);
}
return result;
}
};