Leetcode之Container With Most Water

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/OOC_ZC/article/details/80376237

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.

思路:两个游标在两端,维护一个最大面积。每次移动两个游标中的短的。
时间复杂度O(N)。

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

猜你喜欢

转载自blog.csdn.net/OOC_ZC/article/details/80376237