Last active
December 21, 2018 11:59
-
-
Save sharmaabhinav/d2130fd7e884f778e7da348452575e02 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
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