Skip to content

Commit c77eba3

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

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

42-trapping-rain-water.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,37 @@ const trap = function(height) {
4444
}
4545
return res
4646
}
47+
48+
// another
49+
50+
/**
51+
* @param {number[]} height
52+
* @return {number}
53+
*/
54+
const trap = function(height) {
55+
const len = height.length
56+
if(len === 0) return 0
57+
let left = 0
58+
let right = len - 1
59+
let leftMax = 0
60+
let rightMax = 0
61+
let res = 0
62+
while(left < right) {
63+
if(height[left] < height[right]) {
64+
if(height[left] <= leftMax) {
65+
res += leftMax - height[left]
66+
} else {
67+
leftMax = height[left]
68+
}
69+
left++
70+
} else {
71+
if(height[right] <= rightMax) {
72+
res += rightMax - height[right]
73+
} else {
74+
rightMax = height[right]
75+
}
76+
right--
77+
}
78+
}
79+
return res
80+
};

0 commit comments

Comments
 (0)