Container With Most Water in Java: 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
- Start with widest container (left=0, right=n-1)
- Area is limited by the shorter line
- Moving the taller line inward can only decrease or maintain area
- Moving the shorter line inward might find a taller line → bigger area
Related Data Structures & Algorithms exercises
- Practice Two Sum (Sorted Array) in Java
- Practice Remove Duplicates from Sorted Array in Java
- Practice Three Sum in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler