#11 Container With Most Water

#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.

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.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

利用双指针法,在最左侧设置指针\(i\),最右侧设置指针\(j\)。每次把两者值较小的进行移动,直至两指针相遇。

解释:

对于指针\(i,j\)围成的容器容量我们记作\((i,j)\),则初始状态为\((1,7)\)

为什么我们可以移动较短的指针呢?我们可以看看每一次移动指针我们忽略的状态:对于第一次移动,我们不再计算\((1,8),(1,6),...,(1,8),(1,3)\)。对于这些被忽略的状态,底边的长度一定小于\((1,7)\),而容器的高度最大只可能为\(1\),这说明这些被忽略的状态的容积一定比\((1,7)\)小(底长变小,高变小或不变,矩形面积变小)。

扫描二维码关注公众号,回复: 10060766 查看本文章

由此可以证明此算法的正确性,在尽可能减少计算量的情况下得到结果。

时间复杂度:\(O(n)\),依次遍历

空间复杂度:\(O(1)\),只需储存最大容积即可

代码解释

较为简单,不再解释

Github

猜你喜欢

转载自www.cnblogs.com/LvBaiYang/p/12546846.html