Skip to content

Commit db9387b

Browse files
committed
Add solution #42
1 parent 63a1ce5 commit db9387b

File tree

1 file changed

+6
-17
lines changed

1 file changed

+6
-17
lines changed

solutions/0042-trapping-rain-water.js

+6-17
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,21 @@
33
* https://leetcode.com/problems/trapping-rain-water/
44
* Difficulty: Hard
55
*
6-
* Given `n` non-negative integers representing an elevation map where the width
7-
* of each bar is `1`, compute how much water it can trap after raining.
6+
* Given n non-negative integers representing an elevation map where the
7+
* width of each bar is 1, compute how much water it can trap after raining.
88
*/
99

1010
/**
1111
* @param {number[]} height
1212
* @return {number}
1313
*/
1414
var trap = function(height) {
15-
const leftMax = [];
16-
const rightMax = [];
1715
let result = 0;
1816

19-
leftMax[0] = height[0];
20-
rightMax[height.length - 1] = height[height.length - 1];
21-
22-
for (let i = 1; i < height.length; i++) {
23-
leftMax[i] = Math.max(height[i], leftMax[i - 1]);
24-
}
25-
26-
for (let i = height.length - 2; i > -1; i--) {
27-
rightMax[i] = Math.max(height[i], rightMax[i + 1]);
28-
}
29-
30-
for (let i = 0; i < height.length; i++) {
31-
result += Math.min(leftMax[i], rightMax[i]) - height[i];
17+
for (let left = 0, right = height.length - 1, maxL = 0, maxR = 0; left < right;) {
18+
maxL = Math.max(maxL, height[left]);
19+
maxR = Math.max(maxR, height[right]);
20+
result += maxL < maxR ? maxL - height[left++] : maxR - height[right--];
3221
}
3322

3423
return result;

0 commit comments

Comments
 (0)