Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active December 14, 2015 17:29
Show Gist options
  • Save guolinaileen/5122352 to your computer and use it in GitHub Desktop.
Save guolinaileen/5122352 to your computer and use it in GitHub Desktop.
public class Solution {
public int trap(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
int length=A.length;
if(length==0|| length==1) return 0;
int [] leftMost=new int [length]; int tempL=A[0];
int [] rightMost=new int[length]; int tempR=A[length-1];
int sum=0;
//first pass which stores the right most value
for(int j=length-1; j>=0; j--)
{
if(tempR<A[j])
{
tempR=A[j];
}
rightMost[j]=tempR;
}
//second pass which calculates the right most value and adds the total values
for(int i=1; i<length; i++)
{
if(tempL<A[i])
{
tempL=A[i];
}
leftMost[i]=tempL;
sum+=(A[i]==leftMost[i] || A[i]==rightMost[i] )? 0: Math.min(leftMost[i], rightMost[i])-A[i];
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment