Container With Most Water
Medium · Two pointers
Jump to codeVertical lines stand at consecutive integer x-coordinates with nonnegative heights. Choose two lines that hold the greatest area of water with the x-axis; the water height is the shorter line.
Examples
Example 1
height = [1,8,6,2,5,4,8,3,7]
Output: 49
Example 2
height = [1,1]
Output: 1
Constraints
- 2 <= height.length <= 1000
- 0 <= height[i] <= 1000
Need a hint?
Moving the taller side cannot improve the area while the shorter side stays fixed.
Asked in real interviews
Candidates reported versions of Container With Most Water from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Start at the two ends and record width × minimum height. Move the pointer at the shorter line inward; on a tie, either side may move. Recompute until the pointers meet. A narrower container can win only by improving its limiting height.
Complexity
O(n) time and O(1) extra space.
Python reference solution
def maxArea(height):
left, right, best = 0, len(height) - 1, 0
while left < right:
best = max(best, (right - left) * min(height[left], height[right]))
if height[left] <= height[right]:
left += 1
else:
right -= 1
return best
JavaScript solution
function maxArea(height) {
let left = 0, right = height.length - 1, best = 0;
while (left < right) {
best = Math.max(best, (right - left) * Math.min(height[left], height[right]));
if (height[left] <= height[right]) left++;
else right--;
}
return best;
}
Java solution
import java.util.*;
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1, best = 0;
while (left < right) {
best = Math.max(best, (right - left) * Math.min(height[left], height[right]));
if (height[left] <= height[right]) left++;
else right--;
}
return best;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxArea(vector<int> &height) {
int left = 0, right = (int)height.size() - 1, best = 0;
while (left < right) {
best = max(best, (right - left) * min(height[left], height[right]));
if (height[left] <= height[right]) left++;
else right--;
}
return best;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
1,
8,
6,
2,
5,
4,
8,
3,
7
]
]49
[
[
1,
1
]
]1
[
[
4,
3,
2,
1,
4
]
]16
[
[
1,
2,
1
]
]2
[
[
1,
2,
3,
4,
5
]
]6
Drafts are saved per language in this browser when storage is available.