leetcode 11. Container With Most Water

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.


题目的意思是横坐标上从i=0到i=size-1每个地方有一条垂直于横坐标的线段,参数中的数组就是这些线段的长度。某两个线段和横坐标围成一个二维容器,也就是一个面积,求这个容器的最大容量。

错误解法1:两层循环,遍历所有情况找到最大值,结果超时了。

错误解法2:优化方法1,i为从左往右搜索的指针,j为从右往左的指针,对于每一个i,记录当前j搜索到位置前面,也就是右边的最大线段长度,如果当前线段长度小于这个长度,显然不可能求出最大值,直接进行下一次循环(内层);外层循环同理。结果仍然超时。

正确解法1:贪心算法,为了使容器宽度最大,i,j分别从左从右搜索,为了使容器高度尽量高,如果height[i]>height[j],就j--;因为这样才可能使较短的那个线段更长,否则i++。

int maxArea(int* height, int heightSize) {
    int i,j;
    int max=0;
    int currentArea;
    i=0;
    j=heightSize-1;
    while(i!=j)
    {
        if(height[i]>height[j])
        {
            currentArea=(j-i)*height[j];
            if(currentArea>max)
                max=currentArea;
            j--;
        }
        else
        {
            currentArea=(j-i)*height[i];
            if(currentArea>max)
                max=currentArea;
            i++;
        }
    }
    return max;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值