Container With Most Water in Java: Solution, Explanation & Practice

Find two lines that form container with most water

Problem summary

Given an array of heights, find two lines that together with x-axis form a container that holds the most water. Use two pointers to find the maximum area.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
        
        // Area = min(height[left], height[right]) * (right - left)
        // Move the pointer with smaller height inward
        // Print: Max area: 49
    }
}

Expected output and test cases

  • [1,8,6,2,5,4,8,3,7] → 49
    Max area: 49
  • [1,1] → 1
    Max area: 1
  • [4,3,2,1,4] → 16
    Max area: 16

Hints

  1. Start with widest container (left=0, right=n-1)
  2. Area is limited by the shorter line
  3. Moving the taller line inward can only decrease or maintain area
  4. Moving the shorter line inward might find a taller line → bigger area

Validated solution

Reveal Java solution
public class Main {
    static int maxArea(int[] heights) {
        int left = 0, right = heights.length - 1, best = 0;
        while (left < right) {
            best = Math.max(best, Math.min(heights[left], heights[right]) * (right - left));
            if (heights[left] <= heights[right]) left++; else right--;
        }
        return best;
    }
    public static void main(String[] args) {
        System.out.println("Max area: " + maxArea(new int[] {1, 8, 6, 2, 5, 4, 8, 3, 7}));
    }
}

How to approach the problem

The shorter wall limits an area, so moving the taller wall cannot improve the current limiting height while it always shrinks the width. Move the shorter side and retain the best area observed.

Approach

  1. Start at both ends for maximum possible width.
  2. Calculate width times the shorter height.
  3. Move only the pointer at the shorter wall.

Time and space complexity

Time: O(n). Space: O(1).

Edge cases to test

  • Fewer than two heights have area zero.
  • An equal-height tie can move either side.

Common mistakes

  • Moving both pointers after every calculation.
  • Using the taller height as the water level.

Follow-up challenge

Return the two indices that form the maximum container.

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler