Skip to content

Instantly share code, notes, and snippets.

@GreenSmile
Forked from Zibx/waterfill
Last active December 27, 2015 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GreenSmile/7235895 to your computer and use it in GitHub Desktop.
Save GreenSmile/7235895 to your computer and use it in GitHub Desktop.
var calculate = function( arr ) {
var air_sum = 0;
var ground_sum = 0;
var last = arr.length - 1;
var left_max = arr[0];
var right_max = arr[last];
for ( var i = 0; i <= last; i++ ) {
var el = arr[ i ];
if ( left_max < el ) {
air_sum += ( el - left_max ) * i;
left_max = el;
}
el = arr[ last - i ];
if ( right_max < el ) {
air_sum += ( el - right_max ) * i;
right_max = el;
}
ground_sum += el;
}
var full_sum = left_max * arr.length;
return full_sum - air_sum - ground_sum;
};
// testing
[
[[0,0,0,10,0,0,0,0,0],0],
[[0,1,0,10,0,0,0,0,0],1],
[[1,0,1], 1],
[[5,0,5], 5],
[[0,1,0,1,0], 1],
[[1,0,1,0,1,0,1,0], 3],
[[1,0,1,0], 1],
[[1,0,1,2,0,2], 3],
[[2,5,1,2,3,4,7,7,6], 10],
[[5,1,0,1], 1],
[[2,5,1,2,3,4,7,7,6,3,5], 12]
].forEach(function( el ) {
if( calculate( el[0] ) !== el[1] ) throw( el );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment