[leetcode]11.Container With Most Water

Given n non-negative integers,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.

该问题就是求解构成矩形的最大面积

->想法1:采用两层循环进行遍历,外层i范围0--heightSize-1,里层j范围i+1--heightSize,通过求min(height[i] , height[j]) * (j-i) 和max进行比较,对max进行更新

不足之处:当数据量过大时,乘积的结果超过了int的范围,在leetcode中通过情况为46/49

->想法2:改进方法1的不足。这个题目可以考虑到木桶效应,找到两端的最短点乘以间隔即可。如果起点小于终点,那么短板就是起点,最终点对应的就是最大值,之后起点++; 如果起点大于终点,那么终点就是短板,重点--,只要大于起点,一定能找到该起点对应的最大值。

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




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值