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
Given
[0,1,0,2,1,0,1,3,2,1,2,1], return 6.T:
For each element, it can trap the water whose height is determined by the highest bar from its left and the highest bar from its right. So we can traverse the array by two passes, from left to right to find the left highest bar height and from right to left to find the right highest bar height.
A:
class Solution {
public:
int trap(int A[], int n) {
int maxleft[n];
int maxright[n];
int maxheight = 0;
maxleft[0] = 0;
for(int i=1; i < n; i++) {
if(maxheight < A[i-1]) {
maxheight = A[i-1];
}
maxleft[i] = maxheight;
}
maxheight = 0;
maxright[n-1] = 0;
for(int j=n-2; j>=0; j--) {
if(maxheight < A[j+1]) {
maxheight = A[j+1];
}
maxright[j] = maxheight;
}
int vol = 0;
for(int i=0; i < n; i++) {
vol += max(0, min(maxleft[i], maxright[i]) - A[i]);
}
return vol;
}
};
No comments:
Post a Comment