Container With Most Water Visualizer & Step-by-Step Algorithm Solution

Find two lines that together with the x-axis form a container containing the most water using an optimal O(n) two-pointer inward scan.

Category: arrays | Difficulty: Medium

Tags: Two Pointers, Array, Greedy, Graph, LeetCode 11

Container With Most Water

container capacity
area0
max0
01234567810L8162235445863778Rwidth = 0
Heights Array
L
1
0
8
1
6
2
2
3
5
4
4
5
8
6
3
7
R
7
8
100%
state
heights.length9
left0
right8
heights[left]1
heights[right]7
height0
width0
area0
maxArea0
Start
1/54
Explanation

Begin maxArea on heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]. Scan inward from both ends to find the container holding maximum water.

Source Code
1function maxArea(heights: number[]): number {
2 let left = 0;
3 let right = heights.length - 1;
4 let maxArea = 0;
5 while (left < right) {
6 let height = Math.min(heights[left], heights[right]);
7 let width = right - left;
8 let area = height * width;
9 maxArea = Math.max(area, maxArea);
10 if (heights[left] < heights[right]) left++;
11 else right--;
12 }
13 return maxArea;
14}