File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
container-with-most-water Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } height
3+ * @return {number }
4+ */
5+
6+ // Time Complexity: O(n)
7+ // Space Complexity: O(1)
8+ var maxArea = function ( height ) {
9+ let start = 0 ;
10+ let end = height . length - 1 ;
11+ let maxArea = 0 ;
12+
13+ while ( start < end ) {
14+ const area = ( end - start ) * Math . min ( height [ start ] , height [ end ] ) ;
15+ maxArea = Math . max ( area , maxArea ) ;
16+
17+ // The shorter height limits the area.
18+ // By moving the pointer associated with the shorter height,
19+ // the algorithm maximizes the chance of finding a taller line that can increase the area.
20+ // This is the essence of the two-pointer strategy for the container problem.
21+ if ( height [ start ] < height [ end ] ) {
22+ start += 1 ;
23+ } else {
24+ end -= 1 ;
25+ }
26+ }
27+ return maxArea ;
28+ } ;
29+
You can’t perform that action at this time.
0 commit comments