Problem 11. Container With Most Water
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate ( i, ai). n vertical lines are drawn such that the two endpoints of line i is at ( i, ai) and ( i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
My solution in Python:
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate ( i, ai). n vertical lines are drawn such that the two endpoints of line i is at ( i, ai) and ( i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
My solution in Python:
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ left, right = 0, len(height) - 1 ans = 0 while left < right: if height[left] < height[right]: area = height[left] * (right - left) left += 1 else: area = height[right] * (right - left) right -= 1 ans = max(ans, area) return ans
Review:
This problem belongs to the more simple ones. The trick here is that we don’t really need to examine all combinations of two vertical lines, we only need to discard the shorter one. The height used in calculating area is the shorter one of the two lines, so it does no good to retain the shorter one after computing the current area. We move on and retain the longer line, until the two lines meet.