Container With Most Water

Choose two lines from a row of heights that hold the most water between them.

You are given an array height of n numbers. Each number is a vertical line: line i stands at position i on the ground and is height[i] tall. Pick two lines that, together with the ground between them, hold the most water, and return that amount. The container cannot be tilted.

Example 1
Vertical lines for heights 1, 8, 6, 2, 5, 4, 8, 3, 7, with water held between the lines at positions 1 and 8 Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49
Explanation: the lines at positions 1 and 8 are 7 apart, and the shorter is 7 tall: 7 × 7 = 49.
Example 2
Input: height = [1, 1]
Output: 1
Solution

The Idea

Think of the lines as thin walls standing in a row. Keep any two of them and pour water in between. The water rises until it spills over the lower wall, so the lower wall sets the level. The amount of water is the distance between the two walls times that level.

Take Example 1. The two outer lines, at positions 0 and 8, are as far apart as possible: 8. But the line at position 0 is only 1 tall, so they hold 8 × 1 = 8. The lines at positions 1 and 8 are a little closer, 7 apart, and the lower of them is 7 tall. They hold 7 × 7 = 49, the answer. Look at the picture below.

Lines of heights 1, 8, 6, 2, 5, 4, 8, 3, 7 at positions 0 to 8. Between left at position 1 and right at position 8 the water is 7 wide and 7 high, the height of the shorter line: 7 × 7 = 49.

The blue line at position 1, marked left in the picture, is 8 tall. The orange line at position 8, marked right, is 7 tall, so the water stops at 7, the dashed line. The width is 8 - 1 = 7. The lines in between do not get in the way: they are thin, and the water simply fills around them.

Nine lines can be paired in 36 ways. Measuring all 36 works, but the count grows with the square of the number of lines. So the real question is: can we rule out some pairs without measuring them?

Go back to the outer pair, positions 0 and 8, which hold 8. Every other partner for the line at position 0 is closer to it, so the width is smaller. The level can never be more than 1, because that line is only 1 tall. So no container with the line at position 0 can beat the 8 we just measured. One measurement is enough to rule out that line for good.

That gives the whole plan. Put one marker on each outer line and measure. Then move the marker on the shorter line one step inward and measure again. Searching with two markers that start at opposite ends and move toward each other is called the two-pointer technique. Two Pointers Basics shows other problems where the smaller side is the one to move.

Solution Approach

Turning that idea into code means settling three things: how to measure one container, which line to give up after each measurement, and when to stop.

Measuring one container

What does a container hold? Call the two markers left and right, the positions of the two lines. The width is right - left, and the level is the shorter line, Math.min(height[left], height[right]). Their product is the water.

The simple way measures every pair with two loops, one inside the other. For n lines that is n × (n - 1) / 2 pairs: 36 for nine lines, but about 5 billion for 100,000 lines.

Which line to give up

After measuring left and right, which one should move? The shorter one. Any container that keeps the shorter line and swaps the other for a line further in is narrower, and its level is still at most the shorter line. So it can never hold more than the container just measured, and the shorter line can be dropped.

What if both lines are equally tall? Then the same reasoning holds for each of them, so neither can do better with a closer partner, and moving either one is safe. The code below moves right.

When to stop

Each step moves one marker one position inward, so after at most n - 1 steps the markers meet and no container is left. In Example 1 that means 8 measurements instead of 36. Along the way, a variable best keeps the largest amount measured so far.

Java Solution

The method maxArea works in these steps:

  1. First, put the two markers on the outer lines: left = 0 and right = height.length - 1. Set best to 0.
  2. Start a while loop that runs as long as left is left of right. Inside, measure the water as area, the width times the shorter line, and keep the larger of best and area in best.
  3. Still inside the loop, move the shorter line inward: if height[left] is smaller, left moves right, otherwise right moves left. The else branch also covers equal heights.
  4. When the markers meet, the loop ends; return best.

The main method runs both examples, a row where the best pair sits inside with short lines at both ends, a row whose two outer lines are equally tall, and a row of lines that are all 0 tall.

Java
public class ContainerWithMostWater {

    public static int maxArea(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int best = 0;
        while (left < right) {
            int area = (right - left) * Math.min(height[left], height[right]);
            best = Math.max(best, area);
            if (height[left] < height[right]) {
                left++;                       // the shorter line limits the area: drop it
            } else {
                right--;
            }
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxArea(new int[] {1, 8, 6, 2, 5, 4, 8, 3, 7}));
        System.out.println(maxArea(new int[] {1, 1}));
        System.out.println(maxArea(new int[] {1, 9, 1, 1, 9, 1}));
        System.out.println(maxArea(new int[] {4, 3, 2, 1, 4}));
        System.out.println(maxArea(new int[] {0, 0, 0}));
    }
}

Running it prints:

Output
49
1
27
16
0

Next to 49 and 1 from the two examples, look at the third line, 27, from [1, 9, 1, 1, 9, 1]. Both outer lines are 1 tall, so the markers step past them first and then meet the two lines of height 9, at positions 1 and 4. They are 3 apart: 3 × 9 = 27.

The fourth line, 16, comes from [4, 3, 2, 1, 4]. The outer lines are both 4 tall and 4 apart, so the very first measurement, 4 × 4 = 16, is already the best. Since the heights are equal, right moves, and no narrower container beats 16. The last line is 0: lines that are 0 tall hold no water, whatever their distance.

The direction of the move matters. A version that moves the taller line instead returns 8 for Example 1, not 49. There left stays on the line of height 1, because every line right reaches is taller, so every container it measures is at most 1 high.

The original implementation, ContainerWithMostWater.java, is on GitHub.

Complexity

The work is one walk of the two markers toward each other, with one measurement per step.

  • Time: O(n), where n is the number of lines. Every pass of the loop moves left or right one position inward, so they meet after at most n - 1 passes. Measuring every pair would take O(n²).
  • Space: O(1). The method keeps only the two markers, the current area and best, and never copies the height array.

In Trapping Rain Water, the heights are solid bars, and water collects above every bar, not only between two chosen lines.