Leetcode Hot 1001 分钟
1 次阅读
盛最多水的容器
双指针解法:盛最多水的容器,核心在于移动较矮的边,因为水的高度受限于较矮边,移动它才有可能找到更大容量。

题目

解法
思路
为什么要移动较小的一边?
水的高度总是与较小的一边一样,则此时已经是该边的极限,故可将该边排除,去寻找有无更多水的装法。
答案
class Solution:
def maxArea(self, height: List[int]) -> int:
res = 0
i, j = 0, len(height) - 1
while i < j:
water = abs(i - j) * min(height[i], height[j])
res = max(res, water)
if height[i] < height[j]:
i += 1
else:
j -= 1
return res