Search⌘ K
AI Features

Container with Most Water

Explore how to identify two lines in an array that form the container holding the most water. Learn an optimized two-pointer technique with linear time and constant space complexity to efficiently solve this classic array problem.

Statement

Given an array of heights, which represents the heights of vertical lines drawn on a graph. Find two lines that form a container that holds the most water when combined with the horizontal axis. The height of this container will be the shorter of the two lines:

Note: We cannot tilt any water containers.

Example

Example 1

Sample input

The array below represents the heights of the vertical lines:

[1, 8, 6, 2, 5, 4, 8, 3, 7]

Expected output

49

Example 2

Sample input

The array below represents the heights of the vertical lines:

[1, 1]

Expected output

1

Constraints

The height variable below represents an array of heights of the vertical lines.

2 <= height.length <= 100
0 <= height[i] < 100

Try it yourself

#include <iostream>
#include <vector>
using namespace std;
int MaxWaterAreaContainer(vector<int>& height) {
// TODO: Write - Your - Code
return -1;
}

Solution

We’ll use the following formula to calculate the area of water a container can hold:

Area =  ...