|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function TrappingWater(arr) take the |
| 3 | + * array of non-negative integers stored in arr, and determine the largest |
| 4 | + * amount of water that can be trapped. The numbers in the array represent the |
| 5 | + * height of a building (where the width of each building is 1) and if you |
| 6 | + * imagine it raining, water will be trapped between the two tallest buildings. |
| 7 | + * For example: if arr is [3, 0, 0, 2, 0, 4] then this array of building heights |
| 8 | + * looks like the following picture if we draw it out: |
| 9 | + * |
| 10 | + * [Image of buildings](https://i.imgur.com/PD6xjHs.png) |
| 11 | + * |
| 12 | + * Now if you imagine it rains and water gets trapped in this picture, then |
| 13 | + * it'll look like the following (the x's represent water): |
| 14 | + * |
| 15 | + * [Image of buildings with water](https://i.imgur.com/IL49eNq.png) |
| 16 | + * |
| 17 | + * This is the most water that can be trapped in this picture, and if you |
| 18 | + * calculate the area you get 10, so your program should return 10. |
| 19 | + * |
| 20 | + * https://www.coderbyte.com/results/bhanson:Trapping%20Water:JavaScript |
| 21 | + * |
| 22 | + * @param {array} arr |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +function trappingWater(arr) { |
| 26 | + let maxArea = 0; |
| 27 | + |
| 28 | + for (let a = 0; a < arr.length; a++) { |
| 29 | + for (let b = a + 1; b < arr.length; b++) { |
| 30 | + const maxHeight = Math.min(arr[a], arr[b]); |
| 31 | + |
| 32 | + // Area, ignoring in-between buildings |
| 33 | + let area = (b - a - 1) * maxHeight; |
| 34 | + |
| 35 | + // Now subtract smaller buildings in between |
| 36 | + for (let i = a + 1; i < b; i++) { |
| 37 | + const missingWater = arr[i] > maxHeight ? maxHeight : arr[i]; |
| 38 | + area -= missingWater; |
| 39 | + } |
| 40 | + |
| 41 | + if (area > maxArea) { |
| 42 | + maxArea = area; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return maxArea; |
| 48 | +} |
| 49 | + |
| 50 | +module.exports = trappingWater; |
0 commit comments