Skip to content

Commit 0e4114a

Browse files
authored
Create 42-trapping-rain-water.js
1 parent 4959aae commit 0e4114a

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

42-trapping-rain-water.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number[]} height
3+
* @return {number}
4+
*/
5+
const trap = function(height) {
6+
7+
let s = height.length
8+
if(s === 0) return 0
9+
let res = 0
10+
const left_max = [height[0]]
11+
const right_max = []
12+
right_max[s - 1] = height[s - 1]
13+
for(let i = 1; i < s; i++) {
14+
left_max[i] = Math.max(height[i], left_max[i - 1])
15+
}
16+
for(let i = s - 2; i >= 0; i--) {
17+
right_max[i] = Math.max(height[i], right_max[i + 1])
18+
}
19+
for(let i = 1; i < s - 1; i++) {
20+
res += Math.min(left_max[i], right_max[i]) - height[i]
21+
}
22+
return res
23+
};

0 commit comments

Comments
 (0)