Leetcode (11) The puzzle: Container with the most water

Source: Internet
Author: User

https://leetcode.com/problems/container-with-most-water/

Topic:

Given n non-negative integers A1, A2, ..., an, where each represents a point at Coordi Nate (i, ai). N Vertical Lines is drawn such that the the both endpoints of line I am 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.

Ideas:

Consider reducing the range from the border to the inside. It is important to note that, assuming that the height of the boundary now is a and B, then there are other points in the interior that can be larger than A and B frames, then this point must be larger than the smallest of a and B. So it keeps shrinking from the smaller points of the boundary height until the interior is empty.

Simply iterate through the array once, so the complexity is O (n).

AC Code:

1 classSolution {2  Public:3     intMaxarea (vector<int>&height) {4         intI,j,n=height.size (), a=0, b=n-1, Contain=min (height[0],height[n-1]) * (n1);5          while(a<b) {6             if(height[a]<Height[b]) {7                  for(i=a;i<b;i++){8                     if(height[i]>Height[a])9                          Break;Ten                 } One                 if(min (Height[i],height[b]) * (b-i) >contain) { AContain=min (Height[i],height[b]) * (b-i); -                 } -A=i; the             } -             Else{ -                  for(j=b;j>a;j--){ -                     if(height[j]>Height[b]) +                          Break; -                 } +                 if(min (Height[j],height[a]) * (J-A) >contain) { AContain=min (Height[j],height[a]) * (J-a); at                     } -b=J; -             } -         } -         returncontain; -     } in};

Leetcode (11) The puzzle: Container with the 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.