File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
container-with-most-water Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n)
2+ // Space Complexity: O(1)
3+
4+ var maxArea = function ( height ) {
5+ let left = 0 ;
6+ let right = height . length - 1 ;
7+
8+ // to store the maximum area.
9+ let maxArea = 0 ;
10+
11+ // iterate until the two pointers meet.
12+ while ( left < right ) {
13+ // calculate the width between the two pointers.
14+ let width = right - left ;
15+
16+ // calculate the area with the current area.
17+ let currentArea = Math . min ( height [ left ] , height [ right ] ) * width ;
18+
19+ // update the maximum area if the current area is larger.
20+ maxArea = Math . max ( maxArea , currentArea ) ;
21+
22+ // move the pointer to the shorter line towards the center.
23+ if ( height [ left ] < height [ right ] ) {
24+ left ++ ;
25+ } else {
26+ right -- ;
27+ }
28+ }
29+
30+ // return the maximum area found.
31+ return maxArea ;
32+ } ;
You can’t perform that action at this time.
0 commit comments