-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0042_trapping_rain_water.js
More file actions
33 lines (30 loc) · 961 Bytes
/
0042_trapping_rain_water.js
File metadata and controls
33 lines (30 loc) · 961 Bytes
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
/**
* @link https://leetcode.com/problems/trapping-rain-water/
* @description Given n non-negative integers representing an elevation map
* where the width of each bar is 1, compute how much water it can trap after raining.
* (better see an image at the link)
* @param {Object []} heights
* @returns {Number}
*/
export default (heights) => {
const maxes = new Array(heights.length).fill(0);
let leftMax = 0;
for (let i = 0; i < heights.length; i += 1) {
const height = heights[i];
maxes[i] = leftMax;
leftMax = Math.max(leftMax, height);
}
let rightMax = 0;
for (let i = heights.length - 1; i >= 0; i -= 1) {
const height = heights[i];
const minHeight = Math.min(rightMax, maxes[i]);
if (height < minHeight) {
maxes[i] = minHeight - height;
} else {
maxes[i] = 0;
}
rightMax = Math.max(rightMax, height);
}
const result = maxes.reduce((acc, max) => (acc += max), 0);
return result;
};