-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path042.js
More file actions
36 lines (32 loc) · 786 Bytes
/
042.js
File metadata and controls
36 lines (32 loc) · 786 Bytes
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
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
let maxHeight = 0;
let maxHeightIndex = -1;
for (let i = 0; i < height.length; ++i) {
if (height[i] > maxHeight) {
maxHeight = height[i];
maxHeightIndex = i;
}
}
let waterCount = 0;
let currentMaxHeight = 0;
for (let i = 0; i <= maxHeightIndex; ++i) {
if (height[i] > currentMaxHeight) {
currentMaxHeight = height[i];
} else {
waterCount += (currentMaxHeight - height[i]);
}
}
currentMaxHeight = 0;
for (let i = height.length - 1; i > maxHeightIndex; --i) {
if (height[i] > currentMaxHeight) {
currentMaxHeight = height[i];
} else {
waterCount += (currentMaxHeight - height[i]);
}
}
return waterCount;
};