forked from hijiangtao/LeetCode-with-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathres.js
More file actions
28 lines (24 loc) · 610 Bytes
/
res.js
File metadata and controls
28 lines (24 loc) · 610 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
/**
* @param {number[]} height
* @return {number}
*/
const trap = function(height) {
const len = height.length;
if (len < 3) return 0;
const max_left = [height[0]];
let max_right = [height[len-1]];
let res = 0;
for (let i = 1; i < len; i++) {
max_left[i] = Math.max(height[i], max_left[i-1]);
}
for (let i = len - 2; i >= 0; i--) {
max_right = [Math.max(height[i], max_right[0])].concat(max_right);
}
for (let i = 1; i < len-1; i++) {
const min = Math.min(max_left[i], max_right[i]);
if (min > height[i]) {
res += (min - height[i]);
}
}
return res;
};