1.审题
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.
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.
每一个元素表示一个柱子的高度,两个柱子之间能存的水的取决于柱子之间的宽度,以及左右两个边界柱子中较低的那个。题目要求求出最大的面积。
2. 解题思路
思考套路:
- 暴力求解
- 有没有最小重复问题
- 递归
- 左右夹逼
2.1 暴力求解
两重for循环,计算所有可能,求出最大的面积。
2.2 左右双指针
利用左右夹逼套路,左指针在开始的位置,右指针指向最后的位置,计算面积,更新最大面积。
我们的目标是求最大的面积,最大面积取决于宽度以及最小的柱子的高度。初始状态是宽度最大的时候,但不一定是最大的面积,因为移动指针会使高度变高。
比较左右两个柱子,低的要变高,若低的在左边,左指针向右移动,若低的在右边,右指针往左移动。左指针或者右指针移动一次,更新一次最大面积。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_area = 0
start, end = 0, len(height) - 1
while start < end:
max_area = max(max_area,min(height[start], height[end]) * (end - start))
if height[start] < height[end]:
start += 1
else :
end -= 1
return max_area