LeetCode 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.
解题思路
由题意,要求给定多个容器中能够容纳水的最大量。设定指针first, last分别表示高度的最前端和最后端,在指针每一次移动过程中,都计算当前能够存储的水量,并与之前算得的最大存储量相比较,更新最大存水量。由于容器的体积由较小的边界决定,故求解过程中将高度定义为有效高度,并且如果更新后的容器高度比原来高度低,则求得的存水量必然没有之前的最大存水量大,所以当出现这种情况时,指针继续前移或后移,直到出现更大的容器高度。
源代码
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
water = 0
first = 0
last = len(height) - 1
while first < last:
h = min(height[first], height[last])
water = max(water, (last - first) * h)
while height[first] <= h and first < last:
first += 1
while height[last] <= h and first < last:
last -= 1
return water