-
Notifications
You must be signed in to change notification settings - Fork 0
/
water_tapping.js
68 lines (48 loc) · 1.53 KB
/
water_tapping.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Version 1 of water trapping function
* @param {number[]} height array of height
* @returns number
*/
function trapping (height) {
let trappedWater = 0
height.forEach((elm, i, arr) => {
let tallLeft = elm
for (let index = 0; index <= i; index++) {
const element = arr[index];
if(element> tallLeft) {
tallLeft = element
}
}
let tallRight = elm
for (let index = i+1; index < arr.length; index++) {
const element = arr[index];
if(element> tallRight) {
tallRight = element
}
}
const minHeight = Math.min(tallRight, tallLeft)
trappedWater = trappedWater + (minHeight - elm)
})
return trappedWater;
};
/**
* Optimised water trapping function
* @param {number[]} height array of height
* @returns number
*/
function trappingV2 (height = []) {
let trappedWater = 0
height.forEach((elm, i,) => {
trappedWater = trappedWater + waterTrappedPerHeight(height, i,elm)
})
return trappedWater;
};
function waterTrappedPerHeight (height, i,elm) {
// split heights array into right and left array using the current index
const leftArray = height.slice(0,i+1) // create a left array with current height included
let tallLeft = Math.max(...leftArray) // find the max
const rightArray = height.slice(i) // create a right array with current height included
let tallRight = Math.max(...rightArray) // find the max
const minHeight = Math.min(tallRight, tallLeft)
return (minHeight - elm)
}