16. Container With Most Water
mediumAsked at WisePick two columns that hold the most water — Wise reframes this as picking the two FX liquidity pools that maximize a peer match.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given n non-negative integers where each represents a vertical line at index i with height heights[i], find two lines that, together with the x-axis, contain the most water. Return the maximum area.
Constraints
n == heights.length2 <= n <= 10^50 <= heights[i] <= 10^4
Examples
Example 1
heights=[1,8,6,2,5,4,8,3,7]49Example 2
heights=[1,1]1Approaches
1. All pairs
Try every (i,j) and track the largest min(h[i],h[j])*(j-i).
- Time
- O(n^2)
- Space
- O(1)
let best=0;
for (let i=0;i<heights.length;i++)
for (let j=i+1;j<heights.length;j++)
best=Math.max(best, Math.min(heights[i],heights[j])*(j-i));
return best;Tradeoff:
2. Two-pointer inward
Start at both ends; the shorter side caps area, so move that pointer inward. The optimum is preserved because moving the taller side can never improve the cap.
- Time
- O(n)
- Space
- O(1)
function maxArea(h){
let l = 0, r = h.length - 1, best = 0;
while (l < r){
const area = Math.min(h[l], h[r]) * (r - l);
if (area > best) best = area;
if (h[l] < h[r]) l++; else r--;
}
return best;
}Tradeoff:
Wise-specific tips
Wise wants the invariant-driven two-pointer answer because their FX peer-pooling code applies the same shape — pair the weakest leg first, prune dominated candidates.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Container With Most Water and other Wise interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →