Water Level I
public int waterLevel(int[] array){
//sanity check
if (array.length < 3) return 0;
int left = 0;
int right = array.length - 1;
int lmax = array[left];
int rmax = array[right];
int result = 0;
while (left < right){
if ( array[left] <= array[right] ){
//if cur - lmax not negative, water can be held
result += Math.max(0, lmax - array[left]);
//update lmax in case increase
lmax = Math.max(lmax, array[left];
left++;
} else {
result += Math.max(0, rmax - array[right]);
rmax = Math.max(rmax, array[right]);
right--;
}
}
return result;
}Last updated