Sunday, January 4, 2015

Trapping Rain Water (LeetCode Array)

Question: 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.

Idea: The water trapped at column i is Math.min(maxOnLeft, maxOnRight) - height[i]. So we only need to get the maxOnLeft and the maxOnRight of each column, then accumulate all the water levels. The column 0 and the column last can not trap any water.

Time: O(n) Space: O(n)

Code:
 public class Solution {  
   public int trap(int[] A) {  
     if(A.length<=2)  
       return 0;  
     int[] left=new int[A.length];  
     int[] right=new int[A.length];  
     left[0]=0;  
     for(int i=1;i<A.length;i++)  
     {  
       left[i]=Math.max(left[i-1],A[i-1]);  
     }  
     right[A.length-1]=0;  
     for(int i=A.length-2;i>=0;i--)  
     {  
       right[i]=Math.max(right[i+1],A[i+1]);  
     }  
     int result=0;  
     for(int i=0;i<A.length;i++)  
       result+=Math.max(0,Math.min(left[i],right[i])-A[i]);  
     return result;  
   }  
 }  

No comments:

Post a Comment