easy +15 pts

Container With Most Water

Find the maximum water a pair of vertical lines can hold using the two-pointer technique.

Given a non-negative integer array `heights` where each element represents the height of a vertical line at that index, find the maximum amount of water a container formed by two lines can hold. The container's width is the horizontal distance between the two lines, and its height is the minimum of the two vertical lines. Return the maximum area. The function signature is: `def max_area(heights: List[int]) -> int:`

Constraints

2 <= len(heights) <= 10^5, 0 <= each height <= 10^4. Your solution should run in O(n) time and O(1) space.

Example

>>> max_area([1, 8, 6, 2, 5, 4, 8, 3, 7])
49
>>> max_area([1, 1])
1
>>> max_area([2, 3, 4, 5, 18, 17, 6])
17
15 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Start with two pointers at the two ends of the array.
The area is limited by the shorter line. Move the pointer pointing to the shorter line inward.
Keep track of the maximum area encountered as you move the pointers.
Why does moving the longer line never yield a larger area? (Width decreases, height is capped by the shorter line.)
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.