Skip to content

Commit d9e6fcc

Browse files
authored
Update 42-trapping-rain-water.js
1 parent e2890a5 commit d9e6fcc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

42-trapping-rain-water.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,27 @@ const trap = function(height) {
9393

9494
return res
9595
};
96+
97+
// another
98+
99+
/**
100+
* @param {number[]} height
101+
* @return {number}
102+
*/
103+
const trap = function(height) {
104+
const n = height.length, { max } = Math
105+
let res = 0, l = 0, r = n - 1, leftMax = height[0], rightMax = height[n - 1]
106+
while(l <= r) {
107+
if(leftMax < rightMax) {
108+
leftMax = max(leftMax, height[l])
109+
res += leftMax - height[l]
110+
l++
111+
} else {
112+
rightMax = max(rightMax, height[r])
113+
res += rightMax - height[r]
114+
r--
115+
}
116+
}
117+
118+
return res
119+
};

0 commit comments

Comments
 (0)