Container With Most Water

描述: 

  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;
}    
posted @ 2020-01-07 20:00  一只小菜鸡a  阅读(93)  评论(0)    收藏  举报