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.
这道题数学建模很简单,对于选择i,j,待求的面积即为$$min(a[j],a[i])*(j-i)$$
所以整个问题即转化为$$\forall i < j \in [1,2,...n]\text{, find} max(f(i, j)) = max(min(a[j],a[i])*(j-i)) $$
我们看到了这个问题的是求一个最大值,自然先得到了一个O($n^2$)的解法。
我们再看待求最大值的式子,即$$min(a[j],a[i])*(j-i)$$,乘积的两个因子之间并没有绝对的关系,所以按理说必须$i, j$全部遍历一遍才有可能找到最值。
但是这道题的特殊性在于第一个因子是取min。取min的好处就在于,对于min的操作数中比较大的那个,无论它是多少都不影响这个因子的大小。比如$a[i^*] < a[j^*]$,那么对于这个i来说(固定i),$\forall j \in [i^*+1, j^*] f(i,j) \leq f(i^*,j^*)$ (这个证明很简单),所以我们就不用计算这个$i=i^*$时其他的j值了。我们这时候将i++,再一次比较$a[j],a[i]$即可。
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0, j = height.size()-1, ans = 0;
while (i < j){
ans = max(ans, min(height[i], height[j]) * (j-i));
if (height[i] <= height[j]){
i++;
} else {
j--;
}
}
return ans;
}
};
本文探讨了一道经典的算法问题——给定一系列垂直线段,如何选取两条线段与x轴构成能容纳最多水的容器。通过数学建模,提出了一种高效算法,时间复杂度从O(n^2)优化到O(n)。
143

被折叠的 条评论
为什么被折叠?



