https://leetcode-cn.com/problems/container-with-most-water/
class Solution:
def maxArea(self, height: List[int]) -> int:
maxVal = 0
n = len(height)
for i in range(n):
for j in range(i+1, n):
maxVal = max(min(height[i], height[j]) * (j-i), maxVal)
return maxVal
具体证明见https://leetcode.com/problems/container-with-most-water/solution/
l=0,r=n-1,比较两处高度,较小的往中间移。
可以理解为贪心?height[l]<height[r]
时,若移动较矮的l,虽然宽度变窄,但是可能得到一个更高的从而弥补;若移动较高的r,不一定得到更高的,从而面积减小。
class Solution:
def maxArea(self, height: List[int]) -> int:
maxVal = 0
l, r = 0, len(height)-1
while l < r:
maxVal = max(min(height[l], height[r]) * (r-l), maxVal)
if height[l] < height[r]:
l += 1
else:
r -= 1
return maxVal