LeetCoder_____Container With Most Water(11)

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

题意:

给出一个序列a1,a2,a3......an,每个数字ai表示在(i,0)(i,ai)之间有木杆,也就是一共有n个竖直木杆。我们选取其中两根木杆跟x轴可以构成一个凹形容器,问整个容器体积最大为多少?也就是求:Max(min(ai,aj)*abs(i-j)).

分析:

很显然如果使用两重循环,枚举两根木杆,很简单就可以解决这个问题。但是时间复杂度是O(n^2)。

所以我们需要换一种思路。

假设一开始两根木杆选取最左和最右。无论最优解为何值,我们只要将最左木杆右移,最右木杆左移,总能达到。

但是,是应该让最左木杆右移还是最右木杆左移呢?我们知道无论是left ++还是right -- ,对于abs(right - left) 值都是不变的。

变化的是min(aleft,aright)。所以根据贪心的思想,我们只需要判断left,right对应的两根木头哪个比较短,就移动哪个。然后不断更新最大值。

代码:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left,right,ans;
        left = 0,right = height.size() - 1;
        ans = min(height[left],height[right])*(right-left);
        while(left<right){
            if(height[left]<height[right]){
                left ++;
            }else{
                right --;
            }
            if(min(height[left],height[right])*(right-left)>ans)ans = min(height[left],height[right])*(right-left);
        }
        return ans;
    }
};










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值