-
-
Save GreenSmile/7235895 to your computer and use it in GitHub Desktop.
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
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