Chaturmind
LearnDSASystem DesignDevOpsEngineering GrowthBlog
Start learning
Chaturmind

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

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth

Company

  • Blog
  • 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

The brute force checks every pair of lines directly — O(n^2).

Hint 2

Start with the widest possible container (the two outermost lines) — width can only shrink from here, so it can only get better by improving the height.

Hint 3

Between the two current pointers, moving the TALLER one inward can never help — the container's height is capped by the SHORTER wall regardless, so only shrinking the shorter side has any chance of a bigger area.

Solutions

public int maxAreaBruteForce(int[] height) {
    int maxWater = 0;
    for (int i = 0; i < height.length; i++) {
        for (int j = i + 1; j < height.length; j++) {
            int h = Math.min(height[i], height[j]);
            maxWater = Math.max(maxWater, h * (j - i));
        }
    }
    return maxWater;
}

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