Container with most water

Here's your revised breakdown without emojis, and with a consistent academic tone.


Problem Link

Container With Most Water


Problem Statement (Simplified)

Given an integer array height[] of length n, where each element represents the height of a vertical line drawn at position i on the x-axis.

You need to select two lines such that, together with the x-axis, they form a container that holds the maximum possible amount of water.

Return the maximum area (volume) of water such a container can contain.


Example

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

Explanation:


Intuition


Optimized Two-Pointer Approach (O(n))

Idea


Java Code

class Solution {
    public int maxArea(int[] height) {
        int s = 0;
        int e = height.length - 1;
        int max = 0;

        while (s < e) {
            int h = Math.min(height[s], height[e]);
            int w = e - s;
            int area = h * w;
            max = Math.max(max, area);

            if (height[s] < height[e]) {
                s++;
            } else {
                e--;
            }
        }
        return max;
    }
}

Dry Run

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

Initial: s = 0, e = 8 → min(1, 7) = 1 → area = 1 * 8 = 8
Move s → s = 1

s = 1, e = 8 → min(8, 7) = 7 → area = 7 * 7 = 49 (max updated)
Move e → e = 7

s = 1, e = 7 → min(8, 3) = 3 → area = 3 * 6 = 18
Move e → e = 6

s = 1, e = 6 → min(8, 8) = 8 → area = 8 * 5 = 40
Move e → e = 5

s = 1, e = 5 → min(8, 4) = 4 → area = 4 * 4 = 16
Move e → e = 4

s = 1, e = 4 → min(8, 5) = 5 → area = 5 * 3 = 15
Move e → e = 3

s = 1, e = 3 → min(8, 2) = 2 → area = 2 * 2 = 4
Move e → e = 2

s = 1, e = 2 → min(8, 6) = 6 → area = 6 * 1 = 6
Move e → e = 1

Loop ends. Final max = 49

Time and Space Complexity

Metric Complexity
Time O(n)
Space O(1)

Summary

Strategy Time Complexity Space Complexity Notes
Brute-force (nested loops) O(n²) O(1) Tests all pairs; too slow for large n
Two-pointer (optimal) O(n) O(1) Efficient; uses geometry and logic