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
Given
[0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.Thanks Marcos for contributing this image!
public class Solution { public int trap(int[] A) { // Start typing your Java solution below // DO NOT write main() function int res = 0; if(A.length<3) return res; int[] left = new int[A.length-2], right = new int[A.length-2]; for(int i=0;i<A.length-2;i++) left[i]=i>0?Math.max(left[i-1],A[i]):A[i]; for(int i=A.length-3;i>=0;i--) right[i]=i<A.length-3?Math.max(right[i+1],A[i+2]):A[i+2]; for(int i=0;i<A.length-2;i++){ int temp = Math.min(left[i],right[i]); if(temp>A[i+1]) res+=temp-A[i+1]; } return res; } }
2 comments:
thanks for the solution.
thanks for the solution
Post a Comment