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
题目大意是,给定若干条垂直线,顺着x轴依次排列,要求找出其中最大的装水面积。
解法一:暴力求解
枚举任意两个垂直线,复杂度是O(N^2)。
这个方法很容易理解,不做解释。
解法二:贪心求解
维护左边界 L 和右边界 R ,边界之间的装水面积是 C = min(Input[L], Input[R]) * (R-L)
之后更新左右边界,如果Input[L] < Input[R]
,则左边界+1,否则右边界-1。
复杂度为O(N)。
这个方法很巧妙,但是理解起来不是那么直观。
这也是这道题目最有趣的地方,给大家分享一个理解思路:
可以把这个过程理解为每次减少不必要的计算,
如果Input[L] < Input[R]
,那么[L, R-1]
的装水面积一定小于[L, R]
,思考一下为什么?原因如下:
由于装水面积取决于两个部分:边界间距 R-L
,边界之间的较小者(木桶原理)。
显然[L, R-1]
的边界间距小于[L, R]
,
min(Input[L], Input[R-1]) <= min(Input[L], Input[R])
,这个条件是成立的,不论Input[R-1]
的值是多少。
所以,最终答案一定不在[L, R-1]
内,可以将左边界+1,剩余的可能性存在于[L+1, R]
中。
最后再留一个问题:
如果Input[L] == Input[R]
,此时应该移动哪个边界,为什么?
给出这个题目的链接:
https://leetcode.com/problems/container-with-most-water/description/
欢迎大家关注我的公众号