forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0042-trapping-rain-water.js
96 lines (79 loc) · 2.36 KB
/
0042-trapping-rain-water.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Linear
* Time O(n) | Space O(n)
* https://leetcode.com/problems/trapping-rain-water
* @param {number[]} height
* @return {number}
*
*/
var trap = function(height) {
const maxLeft = [];
const maxRight = [];
const minLeftRight = [];
let current = 0;
for(let i = 0; i < height.length; i++) {
maxLeft.push(current);
current = Math.max(current, height[i]);
}
current = 0;
for(let i = height.length - 1; i > -1; i--) {
maxRight.push(current);
current = Math.max(current, height[i]);
}
// because the elements were added reverse.
maxRight.reverse();
for(let i = 0; i < height.length; i++) {
const minofLeftRight = Math.min(maxLeft[i],maxRight[i]);
minLeftRight.push(minofLeftRight);
}
let water = 0;
for(let i = 0; i < height.length; i++) {
if(minLeftRight[i] - height[i] > 0) {
water += minLeftRight[i] - height[i];
}
}
return water;
};
/**
* https://leetcode.com/problems/trapping-rain-water/
* Time O(N) | Space O(1)
* @param {number[]} height
* @return {number}
*/
var trap = function (height) {
let [left, right] = [0, height.length - 1];
let [maxLeft, maxRight, area] = [0, 0, 0];
while (left < right) {
const [leftHeight, rightHeight] = getHeights(height, left, right);
const [leftWindow, rightWindow] = getWindows(
height,
left,
maxLeft,
right,
maxRight
);
const isRightGreater = leftHeight <= rightHeight;
if (isRightGreater) {
if (hasNewMax(maxLeft, leftHeight)) maxLeft = leftHeight;
else area += leftWindow;
left++;
}
const isRightLess = rightHeight < leftHeight;
if (isRightLess) {
if (hasNewMax(maxRight, rightHeight)) maxRight = rightHeight;
else area += rightWindow;
right--;
}
}
return area;
};
const hasNewMax = (max, height) => max < height;
const getHeights = (height, left, right) => [height[left], height[right]];
const getWindows = (height, left, maxLeft, right, maxRight) => {
const [leftHeight, rightHeight] = getHeights(height, left, right);
const [leftWindow, rightWindow] = [
maxLeft - leftHeight,
maxRight - rightHeight,
];
return [leftWindow, rightWindow];
};