Last active
May 24, 2016 00:48
-
-
Save sranso/3105782f4c50b4a5d9c7f551dcd32fbf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* What this function does: | |
* Given n non-negative integers representing an elevation map where the width of each bar is 1, | |
* compute how much water it is able to trap after raining. | |
*/ | |
function getRainCapacity(array) { | |
var arrayLength = array.length; | |
var water = 0; | |
/* | |
* left contains height of tallest bar up to that point | |
* including itself, going from left to right. | |
* right contains height of tallest bar up to that point | |
* including itself, going from right to left. | |
*/ | |
var left = []; | |
var right = new Array(arrayLength); | |
left[0] = array[0]; | |
for (var i = 1; i < arrayLength; i++) { | |
left[i] = Math.max(left[i-1], array[i]); | |
} | |
right[arrayLength - 1] = array[arrayLength - 1]; | |
for (var i = arrayLength - 2; i >= 0; i--) { | |
right[i] = Math.max(right[i+1], array[i]); | |
} | |
/* | |
* calculate the amount of water trapped at each point in the array | |
*/ | |
for (var i = 1; i < arrayLength; i++) { | |
water += Math.min(left[i], right[i]) - array[i]; | |
} | |
return water; | |
} | |
var input = [2, 5, 1, 2, 4, 7, 2, 1, 4, 6, 9, 4]; | |
console.log(getRainCapacity(input)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment