[leetcode-11]container with most water(C)

问题描述:
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.

分析:问题描述的很清楚,但是却想不明白,还是看了网友的做法才恍然大悟。
area=(right-left)*min(height[right],height[left]);
因此,面积是由两个因素决定的。直接找面积最大的是不可能的,只是是控制变量法,先让边最长,即(right-left)是最大的,即选数组的两端的两条边。此时,height[left] 与height[right]大小会不一样。
假设,height[left] ‘<’ height[right],那么只有当left右移才可能会获取最大面积。因为left边是瓶颈。而当right左移的话,只会使面积减少。

  • 假设height[left]‘<’height[right-1]‘<’height[right],则min(height[right-1],height[left])= height[left].但边却减少,所以面积减少
  • 假设height[right-1]‘<’height[left],则min(height[right-1],height[left])/>height[left].但边却减少,所以面积减少
    所以,只有当left右移时才可能会获得更大值。
    同理,当height[right]‘<’height[left]时,此时,right左移才会获得更大值。

代码如下:12ms

int maxArea(int* height, int heightSize) {
    int left = 0,right = heightSize-1;
    int max = 0;

    int tmp;
    int he;
    while(left<right){
        he = height[left]-height[right];
        if(he<0){
            tmp = (right-left)*height[left];
            left++;
        }else{
            tmp = (right-left)*height[right];
            right--;        
        }
        if(tmp>max)
            max = tmp;
    }
    return max;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值