Last active
August 29, 2015 14:05
-
-
Save oerpli/0ea455e395efa321712e to your computer and use it in GitHub Desktop.
Interpret arbitrary int array as column diagram - pour water over it and output the amount of water that stays on the array. Best Case O(n), Worst Case O(n²), Average Case O(n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fillUp(int[] x){ | |
int total = 0; | |
for(int i = 0;i < x.length-1;i++){ | |
if(x[i] >= x[i+1]){ | |
continue; //if neighbor is higher or equal go to next column | |
} else { | |
int j = 2; //neighbor is known to be lower, so we can start at i+2 | |
bool pool = false; | |
while(i + j < x.length){ | |
if(x[i+j] >= x[i]){ //as soon as a column is at least as big as the reference column | |
pool = true; // mark the found pool. | |
break; | |
} else{ | |
j++; | |
} | |
} | |
if(pool){ | |
int max = x[i] //maximum height of pool | |
for(int y = i;y<i+j;y++){ | |
total += max - x[y]; //fill up | |
} | |
i += j; //jump over to pool to look for the next one | |
} | |
} | |
} | |
Console.WriteLine("Total: " + total); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment