Topic
Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1] , return 6 .
Method
For each a[i],trap water is min (left, right)-a[i];
public int Trap (int[] A) { if (a = = NULL | | A.length = = 0 | | A.length = = 1 | | A.length = = 2) { return 0; } int len = a.length; Int[] left = new Int[len]; Int[] right = new Int[len]; int leftmax = 0; for (int i = 0; i < len; i++) { left[i] = Leftmax; if (A[i] > Leftmax) { Leftmax = A[i]; } } int rightmax = 0; for (int i = len; i > 0; i--) { right[i-1] = Rightmax; if (A[i-1] > Rightmax) { Rightmax = a[i-1]; } } int sum = 0; for (int i = 0; i < len; i++) { int temp = Math.min (Left[i], right[i])-a[i]; if (Temp > 0) { sum + = temp; } } return sum; }
Trapping Rain Water