|
| 1 | +/** |
| 2 | + * @param {number[]} terraces |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | + |
| 6 | +/* |
| 7 | + * STEPS |
| 8 | + * 1. Find the highest terraces on the left and right side of the elevation map: |
| 9 | + * e.g. [0, 2, 4, 3, 1, 2, 4, 0, 8, 7, 0] => (leftMax = 4, rightMax = 8) |
| 10 | + * This is because water will "trail off" the sides of the terraces. |
| 11 | + * |
| 12 | + * 2. At this point, we are essentially dealing with a new map: [4, 3, 4, 2, 4, 0, 8]. |
| 13 | + * From here, we loop through the map from the left to the right (if leftMax > rightMax, |
| 14 | + * otherwise we move from right to left), adding water as we go unless we reach a value |
| 15 | + * that is greater than or equal to leftMax || rightMax. |
| 16 | + * e.g. [4, 3, 4, 2, 4, 0, 8] |
| 17 | + * ^ |
| 18 | + * water += leftMax - 3 => water = 1 |
| 19 | + * or if the terrace array was reversed: |
| 20 | + * e.g. [8, 0, 4, 2, 4, 3, 4] |
| 21 | + * ^ |
| 22 | + * water += rightMax - 3 => water = 1 |
| 23 | + * |
| 24 | + * 3. Again, we've essentially shortened the map: [4, 2, 4, 0, 8]. |
| 25 | + * Now we repeat the above steps on the new array. |
| 26 | + * e.g. |
| 27 | + * Next Iteration: |
| 28 | + * [4, 2, 4, 0, 8] |
| 29 | + * ^ |
| 30 | + * water += leftMax - 2 => water = 3 |
| 31 | + * |
| 32 | + * Next Iteration: |
| 33 | + * [4, 0, 8] |
| 34 | + * ^ |
| 35 | + * water += leftMax - 0 => water = 7 |
| 36 | + * |
| 37 | + * return water(7) |
| 38 | + */ |
| 39 | +export default function rainTerraces(terraces) { |
| 40 | + let start = 0; |
| 41 | + let end = terraces.length - 1; |
| 42 | + let water = 0; |
| 43 | + let leftMax = 0; |
| 44 | + let rightMax = 0; |
| 45 | + |
| 46 | + while (start < end) { |
| 47 | + // Loop to find left max |
| 48 | + while (start < end && terraces[start] <= terraces[start + 1]) { |
| 49 | + start += 1; |
| 50 | + } |
| 51 | + leftMax = terraces[start]; |
| 52 | + |
| 53 | + // Loop to find right max |
| 54 | + while (end > start && terraces[end] <= terraces[end - 1]) { |
| 55 | + end -= 1; |
| 56 | + } |
| 57 | + rightMax = terraces[end]; |
| 58 | + |
| 59 | + // Determine which direction we need to move in |
| 60 | + if (leftMax < rightMax) { |
| 61 | + // Move from left to right and collect water |
| 62 | + start += 1; |
| 63 | + while (start < end && terraces[start] <= leftMax) { |
| 64 | + water += leftMax - terraces[start]; |
| 65 | + start += 1; |
| 66 | + } |
| 67 | + } else { |
| 68 | + // Move from left to right and collect water |
| 69 | + end -= 1; |
| 70 | + while (end > start && terraces[end] <= rightMax) { |
| 71 | + water += rightMax - terraces[end]; |
| 72 | + end -= 1; |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + return water; |
| 77 | +} |
0 commit comments