Container with most water
Here's your revised breakdown without emojis, and with a consistent academic tone.
Problem Link
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:
-
Between index
1(height = 8) and index8(height = 7), the width is7. -
The limiting height is
min(8, 7) = 7. -
Area =
7 * 7 = 49.
Intuition
-
The area between two lines is determined by the distance between the lines (
width) and the shorter of the two heights (min(height[i], height[j])). -
To maximize area:
-
Maximize the width.
-
Maximize the shorter height.
-
-
A brute-force approach would test all pairs, but this is inefficient.
-
The optimal solution involves using two pointers:
-
Start one pointer at the beginning (
left = 0) and the other at the end (right = n - 1). -
Move the pointer pointing to the shorter line inward, hoping to find a taller line that may yield a larger area.
-
Optimized Two-Pointer Approach (O(n))
Idea
-
Initialize two pointers:
left = 0andright = n - 1. -
At each step:
-
Calculate the area:
(right - left) * min(height[left], height[right]). -
Update the maximum area found.
-
Move the pointer pointing to the shorter line inward, since moving the taller one cannot help increase area due to decreasing width.
-
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) |
-
Only a single pass is made through the array.
-
No additional data structures are used.
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 |