Container With Most Water
Medium
Topics
Given an integer array height of length n, find two lines that together with the x-axis form a container holding the most water. Return the maximum area.
Example 1
Bars are wall heights. The shaded rectangle is the best container: its height is the shorter of the two chosen walls and its width is the distance between them.
Input: height = [1,8,6,2,5,4,8,3,7] Output: 49
Example 2
Input: height = [1,1] Output: 1
Constraints
- 2 <= height.length <= 10^5
- 0 <= height[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
The area between two lines is width × min(height_left, height_right). Start with the widest possible container (the two ends).
Moving the taller wall inward can never increase the area (the shorter wall still caps the height while width shrinks). So always move the shorter wall, hoping to find a taller one.
Approach
- Two pointers at the ends; track the best area.
- Compute the current area.
- Move the shorter side inward.
- Stop when the pointers meet.
Walkthrough
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
l=0 r=8: area=8*1=8, move l (1<7)
l=1 r=8: area=7*7=49, move r (7<8)
... best stays 49 -> answer 49Complexity
- Time — O(n): each step moves a pointer inward once.
- Space — O(1): two pointers.
Common Pitfalls
- Move the shorter side inward, never the taller one. Moving the taller side can only keep the height the same or lower it while the width shrinks, so it can never find a bigger area -- flipping that comparison returns 8 instead of 49 on the first example.
- The area uses
minof the two heights, not the height at the pointer being moved. Water is limited by the shorter wall.
Full Solution — all languages
class Solution:
def maxArea(self, nums):
lo, hi, best = 0, len(nums) - 1, 0
while lo < hi:
best = max(best, (hi - lo) * min(nums[lo], nums[hi]))
if nums[lo] < nums[hi]:
lo += 1
else:
hi -= 1
return bestimport java.util.*;
class Solution {
public int maxArea(int[] nums) {
int lo = 0, hi = nums.length - 1, best = 0;
while (lo < hi) {
best = Math.max(best, (hi - lo) * Math.min(nums[lo], nums[hi]));
if (nums[lo] < nums[hi]) lo++;
else hi--;
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxArea(vector<int>& nums) {
int lo = 0, hi = (int)nums.size() - 1, best = 0;
while (lo < hi) {
best = max(best, (hi - lo) * min(nums[lo], nums[hi]));
if (nums[lo] < nums[hi]) lo++;
else hi--;
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var maxArea = function(nums) {
let lo = 0, hi = nums.length - 1, best = 0;
while (lo < hi) {
best = Math.max(best, (hi - lo) * Math.min(nums[lo], nums[hi]));
if (nums[lo] < nums[hi]) lo++;
else hi--;
}
return best;
};