11. The container with the most water
Difficulty: medium
Give you n non-negative integers a 1 , a 2, …, an , and each number represents a point ( i , a i ) in the coordinates . Draw n vertical lines in the coordinates. The two end points of the vertical line i are ( i , a i ) and ( i , 0). Find two of the lines so that the container that they form with the x- axis can hold the most water.
Explanation : You cannot tilt the container, and the value of n is at least 2.
The vertical line in the figure represents the input array [1,8,6,2,5,4,8,3,7]. In this case, the maximum value that the container can hold water (shown as the blue part) is 49.
Example:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
Solution
Double pointers are used here, why can they be used?
- The starting position of the double pointer specifies the search range. The left pointer starts at 0 and the right pointer is len(height)-1, which includes all possible positions .
- Each time you move the pointer, move the corresponding one with the smaller height, and record the water holding volume before each movement. Note : Assuming that the left and right pointers are x and y respectively, height[x]<height[y], so you should move the left pointer next time. This means that height[x] can no longer be used as a new container wall, because if x does not move and the right pointer moves to the left, the new water volume must be smaller than the original . So this is correct.
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l=0
r=len(height)-1
L=[]
while l!=r:
L.append(min(height[l],height[r])*(r-l))
if height[l]<height[r]:
l+=1
else:
r-=1
return max(L)