Skip to content

Commit 6baacc1

Browse files
committed
Added medium/trapping_water
1 parent 97b788e commit 6baacc1

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

medium/trapping_water.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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;

medium/trapping_water.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const trappingWater = require('./trapping_water');
2+
3+
describe('trappingWater()', () => {
4+
test('finds correct area of water that can be trapped', () => {
5+
expect(trappingWater([3, 0, 0, 2, 0, 4])).toBe(10);
6+
7+
expect(trappingWater([1, 2, 1, 2])).toBe(1);
8+
9+
expect(trappingWater([0, 2, 4, 0, 2, 1, 2, 6])).toBe(11);
10+
});
11+
});

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy