leetcode11 盛水容器 贪心

这道题,总感觉做过。。。

先理解题意,何为容器

容器

要求水面高度相同

于是体积就是长方形,高度有两块较高板的低板决定,宽度由两块板间距离决定。

考虑当前最优解,就贪心

从两边开始向内,若能使得体积变大,则取。

贪心策略为移动当前选的两个木板中较短板,这样减少了宽度,但有可能增加高度。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int len=height.size();
        int l=0,r=len-1;
        int temp=(r-l)*min(height[l],height[r]);
        while(l!=r)
        {
            if(height[l]<height[r])
                l++;
            else
                r--;
            temp=max(temp,(r-l)*min(height[l],height[r]));
        }
                     return temp;
    }
};

猜你喜欢

转载自www.cnblogs.com/lqerio/p/11749926.html