File tree Expand file tree Collapse file tree
container-with-most-water Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // Brute Force
2+ // Time Complexity: O(n^2)
3+ // Space Complexity: O(1)
4+ const maxAreaBrute = ( height ) => {
5+ let maxWater = 0 ;
6+ for ( let i = 0 ; i < height . length ; i ++ ) {
7+ for ( let j = i + 1 ; j < height . length ; j ++ ) {
8+ const area = Math . min ( height [ i ] , height [ j ] ) * ( j - i ) ;
9+ maxWater = Math . max ( maxWater , area ) ;
10+ }
11+ }
12+ return maxWater ;
13+ } ;
14+
15+ // Two Pointer
16+ // Time Complexity: O(n)
17+ // Space Complexity: O(1)
18+ const maxArea = ( height ) => {
19+ let left = 0 ;
20+ let right = height . length - 1 ;
21+ let maxWater = 0 ;
22+
23+ while ( left < right ) {
24+ const area = Math . min ( height [ left ] , height [ right ] ) * ( right - left ) ;
25+
26+ maxWater = Math . max ( maxWater , area ) ;
27+
28+ if ( height [ left ] < height [ right ] ) {
29+ left ++ ;
30+ } else {
31+ right -- ;
32+ }
33+ }
34+
35+ return maxWater ;
36+ } ;
You can’t perform that action at this time.
0 commit comments