Container with Most Water
Two pointers — at each step the shorter wall is the bottleneck, so move it inward.
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#
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; }};func maxArea(h []int) int { l, r, best := 0, len(h)-1, 0 for l < r { height := h[l] if h[r] < height { height = h[r] } area := height * (r - l) if area > best { best = area } if h[l] < h[r] { l++ } else { r-- } } return best}from typing import List
class Solution: def maxArea(self, height: List[int]) -> int: l, r, best = 0, len(height) - 1, 0 while l < r: area = min(height[l], height[r]) * (r - l) if area > best: best = area if height[l] < height[r]: l += 1 else: r -= 1 return bestfunction maxArea(height) { let l = 0, r = height.length - 1, best = 0; while (l < r) { const area = Math.min(height[l], height[r]) * (r - l); if (area > best) best = area; if (height[l] < height[r]) l++; else r--; } return best;}class Solution { public int maxArea(int[] height) { int l = 0, r = height.length - 1, best = 0; while (l < r) { int area = Math.min(height[l], height[r]) * (r - l); if (area > best) best = area; if (height[l] < height[r]) l++; else r--; } return best; }}function maxArea(height: number[]): number { let l = 0, r = height.length - 1, best = 0; while (l < r) { const area = Math.min(height[l], height[r]) * (r - l); if (area > best) best = area; if (height[l] < height[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#
Related#