Two Pointers
10. Container With Most Water
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i-th line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Note: You may not slant the container.
Examples
Example 1
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The maximum area of water the container can store is 49.
Example 2
Input: height = [1,1]
Output: 1
Constraints
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4
from typing import List
# Two-pointer approach to find the container that holds the most water
height: List[int] = [1, 3, 7, 5, 3, 2, 6, 9, 1]
max_area: int = 0
l, r = 0, len(height) - 1
while l < r:
area: int = min(height[l], height[r]) * (r - l)
max_area = max(max_area, area)
if height[l] < height[r]:
l += 1
else:
r -= 1
print(max_area) Keyboard shortcuts
← h Previous problem
→ l Next problem
Esc Back to index
? Toggle this help