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.
这道题给出了一个序列,要求找出两根线使其和x轴之间的存储的水最多。注意这里最终盛多少水,不需要考虑中间的最低值,只需要考虑两边的边界。
leetcode给出的提示是用two pointer来做,two pointer做了几题,基本是O(n)复杂度,使用贪心策略。
具体采用何种贪心策略,我也做了好几次选择,最终的选择如下:
1.给出l = 0, r = n-1.
2.当al < ar, l++,向右移动一步,否则 r--,向左移动一步。
首先说明为何采用此种策略。思考如下,转自Yangbing Shi的博客:
由于ai和aj (i<j) 组成的container的面积:S(i,j) = min(ai, aj) * (j-i)
所以对于任何S(i'>=i, j'<=j) >= S(i,j),由于j'-i' <= j-i,必然要有min(ai',aj')>=min(ai,aj)才行。同样可以采用头尾双指针向中间移动:
当a(left) < a(right)时,对任何j<right来说
(1) min(a(left),aj) <= a(left) = min(a(left), a(right))
Here is the proof. Proved by contradiction:
Suppose the returned result is not the optimal solution. Then there must exist an optimal solution, say a container with aol and aor (left and right respectively), such that it has a greater volume than the one we got. Since our algorithm stops only if the two pointers meet. So, we must have visited one of them but not the other. WLOG, let's say we visited aol but not aor. When a pointer stops at a_ol, it won't move until
-
The other pointer also points to aol. In this case, iteration ends. But the other pointer must have visited aor on its way from right end to aol. Contradiction to our assumption that we didn't visit aor.
-
The other pointer arrives at a value, say arr, that is greater than aol before it reaches aor. In this case, we does move aol. But notice that the volume of aol and arr is already greater than aol and aor (as it is wider and heigher), which means that aol and aor is not the optimal solution -- Contradiction!
posted on 2016-05-29 12:19 Sheryl Wang 阅读(227) 评论(0) 编辑 收藏 举报