Trapping Rain Water

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.

class Solution {
public:
    int trap(int A[], int n) {
        int i, res = 0;
        if(!n) return res;
        vector<int> ltr(n, 0), rtl(n, 0);
        for(i = 1, ltr[0] = A[0]; i < n; i++)
            ltr[i] = max(ltr[i-1], A[i]);
        for(i = n - 2, rtl[n-1] = A[n-1]; i >= 0; i--)
            rtl[i] = max(rtl[i+1], A[i]);
        for(i = 0; i < n; i++)
            res += min(ltr[i], rtl[i]) - A[i];
        return res;
    }
};

 

posted on 2014-12-03 21:02  code#swan  阅读(97)  评论(0)    收藏  举报

导航