MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / trap

Function trap

javascript/0042-trapping-rain-water.js:9–40  ·  view source on GitHub ↗
(height)

Source from the content-addressed store, hash-verified

7 *
8 */
9var trap = function (height) {
10 const maxLeft = [];
11 const maxRight = [];
12 const minLeftRight = [];
13
14 let current = 0;
15 for (let i = 0; i < height.length; i++) {
16 maxLeft.push(current);
17 current = Math.max(current, height[i]);
18 }
19 current = 0;
20 for (let i = height.length - 1; i > -1; i--) {
21 maxRight.push(current);
22 current = Math.max(current, height[i]);
23 }
24 // because the elements were added reverse.
25 maxRight.reverse();
26
27 for (let i = 0; i < height.length; i++) {
28 const minofLeftRight = Math.min(maxLeft[i], maxRight[i]);
29 minLeftRight.push(minofLeftRight);
30 }
31
32 let water = 0;
33 for (let i = 0; i < height.length; i++) {
34 if (minLeftRight[i] - height[i] > 0) {
35 water += minLeftRight[i] - height[i];
36 }
37 }
38
39 return water;
40};
41
42/**
43 * https://leetcode.com/problems/trapping-rain-water/

Callers

nothing calls this directly

Calls 5

getHeightsFunction · 0.85
getWindowsFunction · 0.85
hasNewMaxFunction · 0.85
pushMethod · 0.45
reverseMethod · 0.45

Tested by

no test coverage detected