首页 > 其他 > 详细

Container With Most Water

时间:2020-01-07 22:12:41      阅读:73      评论:0      收藏:0      [点我收藏+]

描述: 

  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 and n is at least 2.

解答:

  该道题,求的是最大的面积,最大的面积最终肯定是由某两根棍子组成。因此如果能找出所有两根棍子的组合,

在其中找出最大值的话,则可以求出最大的面积。因此考虑从两个边界向内缩小,这个过程当中会出现所有的组合,

但是在每次移动的过程当中会将较小的组合排除掉,保留较大的值,因为较小的值必然不会是最大的结果,具体的

代码如下:

  

int maxArea(vector<int>& height)
{
    int i=0,j=0;
    int maxarea=0;
    while(i<j)
    {
        area=max(area,min(height[i],height[j])*(j-i));
        //向前移动指针,来更新最大面积的值
        height[i]<height[j] ? i++:j--;
    }   
    return maxarea;
}    

Container With Most Water

原文:https://www.cnblogs.com/wangkaia/p/12163476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!