|
| 1 | +/** |
| 2 | + * @param {number[]} height |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | + |
| 6 | +/* 42. Trapping Rain Water |
| 7 | +https://leetcode.com/problems/trapping-rain-water/ |
| 8 | +
|
| 9 | +Helpful animation of this prompt: https://youtu.be/HmBbcDiJapY?t=51 |
| 10 | +
|
| 11 | +Given n non-negative integers representing an elevation map where |
| 12 | +the width of each bar is 1, compute how much water it is able to trap |
| 13 | +after raining. |
| 14 | +
|
| 15 | +VIEW ELEVATION MAP ON LEETCODE |
| 16 | +
|
| 17 | +Example: |
| 18 | +
|
| 19 | +Input: [0,1,0,2,1,0,1,3,2,1,2,1] |
| 20 | +Output: 6 |
| 21 | +
|
| 22 | +Plan: |
| 23 | +iterate through and find left maxes |
| 24 | +iterate through and find right maxes |
| 25 | +create minheight and assign it to the min(leftmax, rightmax) |
| 26 | +if current height(element) < minheight |
| 27 | + push minheight - height into water array |
| 28 | +else |
| 29 | + push 0 onto water array |
| 30 | +
|
| 31 | +sum up water array and return |
| 32 | +
|
| 33 | +left maxes = [0,0,1,1,2,2,2,2,3,3,3,3] |
| 34 | +right maxes = [3,3,3,3,3,3,3,2,2,2,1,0] |
| 35 | +water contained = [0,0,1,0,1,2,1,0,0,1,0,0] -> sum = 6 |
| 36 | +*/ |
| 37 | + |
| 38 | +function trap (heights) { |
| 39 | + const maxes = new Array(heights.length).fill(0) |
| 40 | + |
| 41 | + let leftMax = 0 |
| 42 | + for (let i = 0; i < heights.length; i++) { |
| 43 | + const height = heights[i] |
| 44 | + maxes[i] = leftMax |
| 45 | + leftMax = Math.max(leftMax, height) |
| 46 | + } |
| 47 | + |
| 48 | + let rightMax = 0 |
| 49 | + for (let i = heights.length - 1; i >= 0; i -= 1) { |
| 50 | + const height = heights[i] |
| 51 | + const minHeight = Math.min(rightMax, maxes[i]) |
| 52 | + |
| 53 | + if (height < minHeight) { |
| 54 | + maxes[i] = minHeight - height |
| 55 | + } else { |
| 56 | + maxes[i] = 0 |
| 57 | + } |
| 58 | + rightMax = Math.max(rightMax, height) |
| 59 | + } |
| 60 | + return maxes.reduce((a, b) => a + b, 0) |
| 61 | +} |
| 62 | + |
| 63 | +console.log(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])) // -> 6 |
0 commit comments