Leetcode-11.盛最多水的容器

607 词

本题采用双指针来解决
矩阵的面积与两个因素有关:
矩阵的长度:两条垂直线的距离
矩阵的宽度:两条垂直线其中较短一条的长度
因此,要矩阵面积最大化,两条垂直线的距离越远越好,两条垂直线的最短长度也要越长越好。

image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:

    def maxArea(self, height: List[int]) -> int:

        i=0

        j=len(height)-1

        maxvolume=0

        while i < j:

            left = height[i]

            right= height[j]

            L=j-i

            currentvolume=min(left,right)*L

            if maxvolume<currentvolume:

                maxvolume=currentvolume

            if left<right:

                i+=1

            else:

                j-=1

        return maxvolume

在每个状态下,无论长板或短板向中间收窄一格,都会导致水槽 底边宽度 −1​ 变短:

若向内 移动短板 ,水槽的短板 min(h[i],h[j]) 可能变大,因此下个水槽的面积 可能增大 。
若向内 移动长板 ,水槽的短板 min(h[i],h[j])​ 不变或变小,因此下个水槽的面积 一定变小 。

因此,初始化双指针分列水槽左右两端,循环每轮将短板向内移动一格,并更新面积最大值,直到两指针相遇时跳出;即可获得最大面积。