Skip to content

Instantly share code, notes, and snippets.

@oerpli
Last active August 29, 2015 14:05
Show Gist options
  • Save oerpli/0ea455e395efa321712e to your computer and use it in GitHub Desktop.
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)
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