[LeetCode系列]最大容器问题

时间:2014-08-15 17:47:19   收藏:0   阅读:344

给定n个数: a1, a2, ... , an. 代表着(i, ai)个点, 连接这些点与对应的(i, 0), 我们可以得到n条线. 请在这n条线中找出2条, 使得这两条线和x轴构成的容器能够容纳最多的水.

本题解法时间复杂度为O(n), 作者是n00tc0d3r.

我们使用2个指针从数组前后开始遍历, 每次循环都计算一次最大值.

当左侧的数比右侧的数小时, 左指针向右挪动一格, 否则, 右指针向左挪动一格.

直到两个指针相遇, 算法结束.

 1 class Solution {
 2 public:
 3     int maxArea(vector<int> &height) {
 4         if (height.size() < 2) return 0;
 5         int maxA = 0;
 6         int low = 0, high = height.size() - 1;
 7         while (low < high) {
 8             int A = (high - low) * min(height[low], height[high]);
 9             maxA = max(A, maxA);
10             if (height[low] < height[high]) 
11                 low++;
12             else
13                 high--;
14         }
15         return maxA;
16     }
17 };

数学证明, 我们使用反证法:

假设返回值并非最优解. 

由假设可得, 必定存在最优解.

假设这个最优解的边界是 aol 和 aor (分别代表左和右). 因为算法仅在两指针相遇时才终止. 所以算法必定访问到某个值的同时没有访问到另一个值.

不失一般性地, 可以假设low访问到了aol, 但high没有访问到aor.

当low指向aol的时候, 它以下条件不满足时不会移动:

bubuko.com,布布扣

综上, 算法返回值必定是最优解.

英文原版说明:

[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

Both cases arrive at a contradiction.]

 

[LeetCode系列]最大容器问题,布布扣,bubuko.com

原文:http://www.cnblogs.com/lancelod/p/3915305.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!