[Problem]
[Solution]
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!
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
int trap(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// initial
int leftBoder[n], rightBoder[n];
// dp
int L = 0, R = 0;
for(int i = 0; i < n; ++i){
if(i == 0){
L = A[i];
R = A[n-1-i];
}
else{
L = L > A[i] ? L : A[i];
R = R > A[n-1-i] ? R : A[n-1-i];
}
leftBoder[i] = L;
rightBoder[n-1-i] = R;
}
// get result
int res = 0, boder;
for(int i = 0; i < n; ++i){
boder = min(leftBoder[i], rightBoder[i]);
if(boder > A[i])res += boder - A[i];
}
return res;
}
};