扫描leftmost和rightmost
class Solution { public: int trap(int A[], int n) { if(n < 3) return 0; vector<int> left(n , 0); vector<int> right(n , 0); //left most for(int i = 1 ; i < n ; i++) { left[i] = max(left[i-1] , A[i-1]); } //right most for(int i = n- 2 ; i >= 0 ; i--) { right[i] = max(right[i + 1] , A[i+1]); } int sum = 0; for(int i = 0 ; i < n ; i++) { int maxH = min(left[i] , right[i]); if(maxH > A[i]) sum += maxH - A[i]; } return sum; } };
by 1957