Skip to content

Commit 6e234a4

Browse files
committed
Runtime: 53 ms (Top 86.36%) | Memory: 44.80 MB (Top 38.62%)
1 parent 00a45e3 commit 6e234a4

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,26 @@
1+
// Runtime: 53 ms (Top 86.36%) | Memory: 44.80 MB (Top 38.62%)
2+
13
var trap = function(height) {
2-
let left = 0, right = height.length - 1;
3-
let hiLevel = 0, water = 0;
4-
while(left <= right) {
5-
let loLevel = height[height[left] < height[right] ? left++ : right--];
6-
hiLevel = Math.max(hiLevel, loLevel);
7-
water += hiLevel - loLevel ;
4+
let landArea = 0;
5+
let maxFromLeft = 0;
6+
let maxAreaFromLeft = 0;
7+
8+
for (let h of height) {
9+
landArea += h;
10+
maxFromLeft = Math.max(maxFromLeft, h);
11+
maxAreaFromLeft += maxFromLeft;
812
}
9-
return water;
13+
14+
let maxFromRight = 0;
15+
let maxAreaFromRight = 0;
16+
17+
for (let i = height.length - 1; i >= 0; i--) {
18+
maxFromRight = Math.max(maxFromRight, height[i]);
19+
maxAreaFromRight += maxFromRight;
20+
}
21+
22+
const boundingArea = height.length * maxFromLeft;
23+
const leftVoid = boundingArea - maxAreaFromLeft;
24+
const rightVoid = boundingArea - maxAreaFromRight;
25+
return boundingArea - leftVoid - rightVoid - landArea;
1026
};

0 commit comments

Comments
 (0)