Container with Most Water

Two pointers — at each step the shorter wall is the bottleneck, so move it inward.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
two-pointers array greedy

Problem#

Each index i has height h[i]. Pick two indices forming a container; the water held is min(h[i], h[j]) * (j - i). Maximize this.

Examples#

  • [1,8,6,2,5,4,8,3,7]49.
  • [1,1]1.

Constraints#

  • 2 <= n <= 10^5.

Approach#

Two pointers at both ends. Move the pointer at the shorter wall inward — the shorter wall is the bottleneck and any narrower container that keeps it can only shrink.

Solution#

Container with Most Water
class Solution {
public:
int maxArea(vector<int>& h) {
int l = 0, r = h.size() - 1, best = 0;
while (l < r) {
int area = min(h[l], h[r]) * (r - l);
best = max(best, area);
if (h[l] < h[r]) ++l; else --r;
}
return best;
}
};

Editorial#

The proof of correctness: keeping the shorter wall fixed cannot improve area (width shrinks, height is still capped by the short wall). So we never need to consider any pair containing the shorter wall as one end again — safely advance it inward.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.