Skip to content

Instantly share code, notes, and snippets.

@KodeSeeker
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save KodeSeeker/87a478d731218fd4c8e0 to your computer and use it in GitHub Desktop.

Select an option

Save KodeSeeker/87a478d731218fd4c8e0 to your computer and use it in GitHub Desktop.
Pour water over a histogram. Find the amount of water accumulated in the gaps.
/*
Image URL for representation :http://www.darrensunny.me/wp-content/uploads/2014/04/Rain-Water-Trap.png
Algo: From left compute the max of the current element and the elements on the left. and store in array : maxLeft[]
From right move left and compute the max of current element and the element on right
for each element and store in array: maxRight[].
The amount of water above each element is Min(maxleft[i],maxRight[i])-hist[i].
Assumption width of each histogram bar is 1.
Time complexity: O(n).
**/
public int getWaterinHistogram(int[] hist)
{
if(hist==null||hist.length==0||hist.length==1)
return 0;
int [] maxLeft= new int[hist.length];
int [] maxRight= new int[hist.length];
int len= hist.length;
//compute maxLeft
for(int i=0; i< hist.length;i++)
{
maxLeft[i] = (i==0?hist[i] :Math.max(maxLeft[i-1],hist[i])); // i=0 is the base case. here maxLeft[i]=hist[i]
}
//compute maxRight.-- fill array from right.
for(int i=len-1;i>=0;i--)
{
maxRight[i]=(i==len-1? hist[i]: Math.max(maxRight[i+1],hist[i]));// i=len-1 is the base case. here maxRight[i]=hist[i]
}
//now to calculate amount of water stored
int volume=0;
for(int i=0;i<len-1;i++)
{
volume +=Math.min(maxRight[i],maxLeft[i])-hist[i]
}
return volume;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment