File tree 1 file changed +23
-7
lines changed
scripts/algorithms/T/Trapping Rain Water
1 file changed +23
-7
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 53 ms (Top 86.36%) | Memory: 44.80 MB (Top 38.62%)
2
+
1
3
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 ;
8
12
}
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 ;
10
26
} ;
You can’t perform that action at this time.
0 commit comments