MediumLeetCode #11Two Pointers
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 ith 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.
Constraints
n == height.length, 2 <= n <= 10^5, 0 <= height[i] <= 10^4
Examples
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Solution
Approach
Use two pointers at both ends. Calculate area and move the pointer pointing to the shorter line inward (greedy: we can only potentially improve by moving the shorter side).
def maxArea(height):
left, right = 0, len(height) - 1
max_area = 0
while left < right:
width = right - left
h = min(height[left], height[right])
max_area = max(max_area, width * h)
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_areaComplexity
Time:O(n)
Space:O(1)
Hints
- 1.Area is limited by the shorter line
- 2.Start with widest container
- 3.Moving shorter line might find taller one
Asked at
Google