Skip to content

Commit 347110a

Browse files
authored
Update 42-trapping-rain-water.js
1 parent c44a622 commit 347110a

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

42-trapping-rain-water.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,26 @@ const trap = function(height) {
2121
}
2222
return res
2323
};
24+
25+
// another
26+
27+
/**
28+
* @param {number[]} height
29+
* @return {number}
30+
*/
31+
const trap = function(height) {
32+
const len = height.length
33+
if (len === 0) return 0
34+
const leftMax = [height[0]]
35+
const rightMax = []
36+
rightMax[len - 1] = height[len - 1]
37+
for (let i = len - 2; i >= 0; i--) {
38+
rightMax[i] = Math.max(height[i], rightMax[i + 1])
39+
}
40+
let res = 0
41+
for (let i = 1; i < len; i++) {
42+
leftMax[i] = Math.max(height[i], leftMax[i - 1])
43+
res += Math.min(leftMax[i], rightMax[i]) - height[i]
44+
}
45+
return res
46+
}

0 commit comments

Comments
 (0)