11. Container With Most Water

Given n non-negative integers a 1 , a 2 , . . . , a n , where each represents a point at coordinate ( i , a i ) . n vertical lines are drawn such that the two endpoints of line i is at ( i , a i ) 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.

以头尾两根为基准(底最长),其他组合要大于此容积必须大于它的高(取决于短板)

class Solution {
public:
    int maxArea(vector<int>& height) {
        int n = height.size();
        int i = 0, j = n - 1;
        int maxC = INT_MIN;
        while(i < j)
        {
            int minH = min(height[i] , height[j]);
            maxC = max(maxC , minH * (j - i));
            while(height[i] <= minH && i < j)
                i ++;
            while(height[j] <= minH && i < j)
                j --;
        }
        return maxC;
    }
};

猜你喜欢

转载自blog.csdn.net/chineseqsc/article/details/80007093