- Link: 11. Container With Most Water - Medium
- Track: Amazon
Question
Restate
- Given an integer array
height, whereheight[i]is the height of a vertical line ati - Choose two lines with x-axis, form a container
- Find two lines that contain the most water
- Return the maximum area
Edge Case
len(height) < 2- All equal heights (e.g.,
[5,5,5]) → widest pair is optimal
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Two Pointers |
Method 1 - Two Pointers
Approach
Key idea:
- The water area is limited by the shorter line
- To possibly increase the area, always move the pointer at the shorter line
- Use two pointers
left(start) andright(end) - At each step:
- Compute area using the current pair.
- Update
res. - Move the pointer at the shorter height inward:
- Because width decreases no matter what; the only chance to get a bigger area is to potentially increase the limiting height
min(...). - Moving the taller side cannot increase
min(...)when the shorter side stays the same, so it can’t lead to a better area than the current width.
- Because width decreases no matter what; the only chance to get a bigger area is to potentially increase the limiting height
Complexity
- Time Complexity:
- Space Complexity:
Code
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
res = 0
while left < right:
high = min(height[right], height[left])
area = (right - left) * high
res = max(res, area)
if height[left] < height[right]:
left += 1
else:
right -= 1
return resCommon Mistake
- Using
while left <= right(whenleft == right, width is0, no need to compute)