Container with most water

Source: Internet
Author: User

At the beginning of the violent settlement, the time did not pass

1 classSolution {2  Public:3     intMaxarea (vector<int>&height) {4         intMaxarea=0, eacharea=0;5         if(Height.size () <2)returnMaxarea;6          for(intI=0; I)7             for(intj=i+1; J)8            {9Eacharea= (Height[i]>height[j]?height[j]:height[i]) * (J-i);Ten              if(Eacharea>maxarea) maxarea=Eacharea; One            } A         returnMaxarea; -     } -};

Later to see the great God's explanation, found that the problem principle is super simple:

The so-called container can be regarded as a rectangular box, we first put the integer capacity as one side of the length, the two shortest high as the other side of the long side, then get a rectangular area. Later to find larger than this area, when the side of the rectangle shrinks, then only the other side of the length of the larger, the overall area is likely to become larger. Therefore, when the container from two to the middle of the narrowing, you have to find the shortest side than the two long-test. So the last time complexity is O (n)

Here's the code:

1 classSolution {2  Public:3     intMaxarea (vector<int>&height) {4     intWater=0, H;5     intI=0, J=height.size ()-1;6      while(i<j)7     {8H=min (height[i],height[j]);9         if(wateri);Ten          while(height[i]<=h && i<j) i++; One          while(height[j]<=h && i<j) j--; A     } -     returnwater; -     } the      -};

Container with most water

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.