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.
∀1<=i, j<=n, 不妨令ai < aj, 则以ai和aj为边界的container所盛水的侧面积最大为A(i, j)= (j-i)*min(ai, aj) = (j-i)*ai;
此时∀1<=i<= k <=j<=n; A(i, k) = (k-i)*min(ai, ak) <= (k-i)*ai <=(j-i)*ai = A(i, j)
这就是木桶效应。
int maxArea(vector<int> &height) {
int i=0,j=height.size()-1,result = 0;
while(i<j){
result = height[i]>=height[j] ? max(result,(j-i)*height[j--]) : max(result, (j-i)*height[i++]);
}
return result;
}
从两端向中间搜索,比较h[i]和h[j],一旦确定哪个较小了,记录其围城的木桶盛水侧面积,然后就可以抛弃较小的h值,将其替换为另一个h值,因为此时无论怎么替换那个较大的h值,根据木桶效应,是不会增大桶的盛水量的,桶的盛水量取决于短板而不是长板的高度,只有替换掉短板,桶的盛水量才有可能增大。因此每次记录完盛水侧面积后抛弃较小的h值,并不会丢失使盛水量更大的解,从而可以省去大量不必要的搜索,令原本需要两两匹配的O(n^2)的时间复杂度降为O(n),实现复杂度也并没有提高。