MediumNo. 0011
Container With Most Water — LeetCode 11 Python Solution
- Pattern
- Two Pointers
- Topics
- Greedy, Array, Two Pointers
- On study lists
- Blind 75, NeetCode 150, Grind 75, LeetCode 75 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Example
- Input
- height = [1,8,6,2,5,4,8,3,7]
- Output
- 49
- Explanation
- The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Python solution
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
ans = 0
while l < r:
t = min(height[l], height[r]) * (r - l)
ans = max(ans, t)
if height[l] < height[r]:
l += 1
else:
r -= 1
return ansComplexity
- Time
- O(n)where n is the length of the array height
- Space · auxiliary
- O(1)
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 11. Container With Most Water is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0455 | Assign Cookies | Easy |
| 0611 | Valid Triangle Number | Medium |
| 0826 | Most Profit Assigning Work | Medium |
| 0870 | Advantage Shuffle | Medium |
| 0881 | Boats to Save People | Medium |
| 0942 | DI String Match | Easy |
Frequently asked questions
- How hard is LeetCode 11. Container With Most Water?
LeetCode 11. Container With Most Water is rated Medium on LeetCode.
- What is the time complexity of LeetCode 11. Container With Most Water?
The Python solution on this page runs in O(n), where n is the length of the array \textit{height}.
- What is the space complexity of LeetCode 11. Container With Most Water?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 11. Container With Most Water cover?
LeetCode 11. Container With Most Water is tagged Greedy, Array and Two Pointers on LeetCode.