Trapping Rain Water
DP.
O(n) solution.
对于每个bar,找出其左边与右边的最高高度, 可以hold的water = min(max_left, max_right) - height
int trap(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int maxHeight = 0; vector<int> left(n); for(int i=0;i<n;i++) { left[i] = maxHeight; maxHeight = max(maxHeight,A[i]); } maxHeight = 0; vector<int> right(n); for(int i=n-1;i>=0;i--) { right[i] = maxHeight; maxHeight = max(maxHeight,A[i]); } int water = 0; for(int i=0;i<n;i++) { int height = min(left[i],right[i]) - A[i]; if(height<0) height = 0; water += height; } return water; }