Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Arrays›Container With Most Water
MediumArrays

Container With Most Water

arraytwo-pointersgreedy

Problem

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container that holds the most water.

Return the maximum amount of water a container can store.

Examples

Example 1

Input: height = [1,8,6,2,5,4,8,3,7]

Output: 49

Explanation: Lines 2 and 9 form a container of min(8,7)*7=49.

Constraints

  • •n == height.length
  • •2 <= n <= 10^5
  • •0 <= height[i] <= 10^4

Hints

Hint 1

Use two pointers from both ends. Move the pointer with the smaller height inward.

Solutions

public int maxArea(int[] height) {
    int left = 0, right = height.length - 1;
    int maxWater = 0;
    while (left < right) {
        int h = Math.min(height[left], height[right]);
        maxWater = Math.max(maxWater, h * (right - left));
        // Move the shorter side — moving the taller side can only decrease area
        if (height[left] < height[right]) left++;
        else right--;
    }
    return maxWater;
}
Java

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