Skip to content

Commit a3382d9

Browse files
authored
Update 42-trapping-rain-water.js
1 parent cbde64d commit a3382d9

File tree

1 file changed

+12
-22
lines changed

1 file changed

+12
-22
lines changed

42-trapping-rain-water.js

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -52,29 +52,19 @@ const trap = function(height) {
5252
* @return {number}
5353
*/
5454
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++
55+
const n = height.length
56+
let l = 0, r = n - 1, res = 0, leftMax = 0, rightMax = 0
57+
while(l <= r) {
58+
if(height[l] <= height[r]) {
59+
if(height[l] >= leftMax) leftMax = height[l]
60+
else res += leftMax - height[l]
61+
l++
7062
} else {
71-
if(height[right] <= rightMax) {
72-
res += rightMax - height[right]
73-
} else {
74-
rightMax = height[right]
75-
}
76-
right--
63+
if(height[r] >= rightMax) rightMax = height[r]
64+
else res += rightMax - height[r]
65+
r--
7766
}
7867
}
7968
return res
80-
};
69+
};
70+

0 commit comments

Comments
 (0)