Scanning from left to right and right to left.

Find the max height of left and right. The minimum one will be most possible height for current state that can bound the water. But one thing need to check:

whether current height is higher than the value.

 1 class Solution {
 2 public:
 3     int trap(int A[], int n) {
 4         if (n < 3) return 0;
 5         vector<int> left(n), right(n);
 6         int result = 0, rec = A[0];
 7         for (int i = 1; i < n; i++) {
 8             left[i] = max(rec, left[i-1]);
 9             rec = max(rec, A[i]);
10         }
11         rec = A[n-1];
12         for (int i = n-2; i >= 0; i--) {
13             right[i] = max(rec, right[i+1]);
14             rec = max(rec, A[i]);
15         }
16         for (int i = 0; i < n; i++) {
17             result += (min(left[i], right[i]) - A[i]) > 0 ? (min(left[i], right[i]) - A[i]) : 0;
18         }
19         return result;
20     }
21 };

 

posted on 2015-03-24 17:06  keepshuatishuati  阅读(131)  评论(0编辑  收藏  举报