[leetcode] Trapping Rain Water

Trapping Rain Water

class Solution {
public:
    int trap(int A[], int n) {
        if(n<=0){
            return 0;
        }
        
        int tmp[n];
        int curMax=A[0];
        int res=0;
        for(int i=0;i<n;i++){//从左往右扫描
            if(A[i]>=curMax){
                curMax=A[i];
                tmp[i]=0;
            }else{
                tmp[i]=curMax-A[i];
            }
        }
        
        curMax=A[n-1];
        for(int j=n-1;j>=0;j--){//从右向左扫描
            if(A[j]>=curMax){
                curMax=A[j];
                tmp[j]=0;
            }else{
                tmp[j]=min(tmp[j],curMax-A[j]);
            }
        }
        
        for(int k=0;k<n;k++){
            res+=tmp[k];
        }
        return res;
    }
};


你可能感兴趣的:([leetcode] Trapping Rain Water)