Skip to content

Instantly share code, notes, and snippets.

@Shaxadhere
Created March 6, 2023 14:04
Show Gist options
  • Save Shaxadhere/7a9b8ffbb54e88cc1c3abcefeae7bdcb to your computer and use it in GitHub Desktop.
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.
/**
* @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