

LeetCode 11. Container With Most Water
source link: https://gongzq5.github.io/posts/LeetCode-11-Container-With-Most-Water-2020-02-14/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode 11. Container With Most Water
链接给到 https://leetcode-cn.com/problems/container-with-most-water/
给定 n 个非负整数a1,a2,…,an,每个数代表坐标中的一个点(i,ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i,ai) 和 (i,0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
输入: [1,8,6,2,5,4,8,3,7]
输出: 49
正确的方法是,开始时将两个线放在两边,然后每次都将较短的那根线向内移动,同时更新最大面积;
我们可以简单的证明这个解法的正确性:
简单说明一下,i,j 即左右两个端点。
最后我们可以确定,原来的面积为3h0:
- 如果hx>h0,那么面积为 xh0,明显是小于 3h0的;
- 而如果 hx<h0 的话,一方面x<3,另一方面 hx<h0,所以肯定也是小于 3h0的;
我只证明了,当 i 按照我们的方式移动时,不会错过任何的情况;
很明显,j 也是一样的道理,所以我们的解法是不会错过最优解的。
class Solution:
def maxArea(self, height: List[int]) -> int:
themax = 0
i1, i2 = 0, len(height) - 1
while i1 < i2:
area = (i2 - i1) * min(height[i2], height[i1])
if area > themax:
themax = area
if height[i1] < height[i2]:
i1 += 1
else:
i2 -= 1
return themax
Recommend
-
9
Leetcode 11. Container With Most Water 当前位置:XINDOO > 算法 > 正文 Given n non-negative in...
-
7
Leetcode 365. Water and Jug Problem 当前位置:XINDOO > 编程 > 正文
-
9
题目¶ 原题地址:https://leetcode.com/problems/most-frequent-subtr...
-
8
Leetcode 42 接雨水 (Trapping Rain Water) 题解分析 Posted on 2021-07-04 In Java , leetcode Views: 52 Views: 57 Dis...
-
5
Back to Leetcode after a week. I am doing a Spring Microservices course in parallel which is going to take more of my challenge time. However, wanted to do something different today. Day 16 - Container With Most Water
-
6
Problem statement Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Problem statement taken from:
-
3
Posted 2 years agoUpdated 2 months agoLeetCode
-
6
Smart water bottles may be useful for some, but most c...
-
6
Heritage This Yorkshire River Is Home To The ‘Deadliest Stretch Of Water In The World’
-
7
Meet the most awaited CSS container queries Sep 29, 2022 , by Chetan Gawai 5 minute read Rendering webs...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK