Created
March 6, 2023 14:04
-
-
Save Shaxadhere/7a9b8ffbb54e88cc1c3abcefeae7bdcb to your computer and use it in GitHub Desktop.
this is my attempt to solve trapping water with javascript, but it fails at 319th test case, saved this just in case i feel about improving the solution later.
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
/** | |
* @param {number[]} height | |
* @return {number} | |
*/ | |
var trap = function (height) { | |
function measureWater(currentValue, prevItems, nextItems) { | |
const lastPrev = isFinite(Math.max(...prevItems)) ? Math.max(...prevItems) : 0 | |
const lastNext = isFinite(Math.max(...nextItems)) ? Math.max(...nextItems) : 0 | |
const smallerRL = lastPrev >= lastNext ? lastNext : lastPrev | |
let block = currentValue | |
let water; | |
if (smallerRL === 0) water = 0 | |
else if (smallerRL < block) water = 0 | |
else water = block - smallerRL | |
return water | |
} | |
let sum = 0 | |
height.forEach((item, index) => { | |
let nextItems = [...height].slice(index + 1, height.length); | |
let prevItems; | |
if (index === 0) { | |
prevItems = [] | |
} else if (index === 1) { | |
prevItems = [height[0]] | |
} else if (index > 1) { | |
prevItems = [...height].slice(0, index) | |
} | |
sum += Math.abs(measureWater(item, prevItems, nextItems)) | |
}) | |
return sum | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment