Container with most water:

Source: Internet
Author: User

GivenNnon-negative integersa1 ,a2 , ...,an , where each represents a point at coordinate (I,ai ).NVertical lines is drawn such that the both endpoints of lineIis at (I,ai ) and (I, 0). Find lines, which together with X-axis forms a container, such that the container contains the most water.

Note:you may not slant the container.

Interpretation of the topic:

There are n non-negative numbers, representing the height of the N water barrier plate, now for the maximum capacity of two water-barrier, that is, to find a pair of water-plate, distance *min (two water barrier height) maximum.

Problem-Solving ideas: Method One: The code of the poor lifting method is as follows:
Class Solution {public:    int Maxarea (vector<int>& height) {        int length=height.size ();        if (length<=1) return 0;        int cap=0;        for (int i=0;i<length-1;i++)        {for            (int j=i+1;j<length;j++)            {                if (min (Height[i],height[j]) * ( j-i) >cap)                cap=min (Height[i],height[j]) * (j-i);            }        }        return cap;    }};
The method is straightforward, but there is a timeout. Method Two: The maximum distance of two partitions of the water storage, when the distance is reduced, want to increase the amount of water, the minimum height of the partition should be increased accordingly. Using this idea, we have the following code:
Class Solution {public:    int Maxarea (vector<int>& height) {        int length=height.size ();        if (length<=1) return 0;        int cap=0;        int left=0,right=length-1;        while (Left<right)        {            if (min (Height[left],height[right]) * (right-left) >cap)            Cap=min (height[left ],height[right]) * (right-left);            if (Height[left]



Container with most water:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.