Skip to content

Instantly share code, notes, and snippets.

@sharmaabhinav
Last active December 21, 2018 11:59
Show Gist options
  • Save sharmaabhinav/d2130fd7e884f778e7da348452575e02 to your computer and use it in GitHub Desktop.
Save sharmaabhinav/d2130fd7e884f778e7da348452575e02 to your computer and use it in GitHub Desktop.
var arr = [];
for(var i=100000;i>=1;i--) {
arr.push(i);
}
for(var i=1;i<=100000;i++) {
arr.push(i);
}
console.log(arr)
function calWater (arr) {
var cur = null
var next = null
let waterTrapped = 0
for(var start = 0; start < arr.length;) {
var {index, sum} = findNextIndex(arr, start)
if (index !== -1) {
waterTrapped += Math.min(arr[start], arr[index]) * (index - start-1) - sum
start = index
} else {
start++
}
}
return waterTrapped
}
function findNextIndex (arr, index) {
var start = index + 1
var sum = 0
while(start < arr.length) {
if (arr[start] >= arr[index]) {
return { index: start, sum}
} else {
sum += arr[start]
}
start += 1
}
return {index: -1, sum}
}
console.log(calWater(arr))
/*
for each elment find next element which is equal or greatet than current hi
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment