Leetcode | | Container with most water issues

Source: Internet
Author: User

Problem:

Given n non-negative integers a1, A2, ..., an, where each represents a point at coordinate (I, AI). n vertical lines is drawn such, the and the other 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.

The x-axis is the bottom, two longitudinal axes are changed, the volume of the container is obtained, and the short edge is the bottleneck.


Thinking:

(1) The short side determines the effective height of the tank, the bottom to be as wide as possible.

(2) A typical double-pointer solution.

(3) Greedy strategy, which side is short, narrowing in the search for the next edge.

Code

Class Solution {public:    int Maxarea (vector<int> &height) {        //Start Typing your C + + solution Below
   //does not write int main () function        int i = 0;        Int J = height.size ()-1;                int ret = 0;        while (I < j)        {            int area = (j-i) * min (Height[i], height[j]);            RET = max (ret, area);                        if (Height[i] <= height[j])                i++;            else                j--;        }                return ret;    }};

Time Complexity of O (n)



Brute force method: Time Complexity O (n*n)

int area (Vector<int>::iterator &a,vector<int>::iterator &b) {    return (b-a) * (*a>*b?*b:*a) ;} Class Solution {public:    int Maxarea (vector<int> &height) {        int max_area=0;        For (Vector<int>::iterator I=height.begin () +1;i!=height.end (), i++)        {for            (VECTOR<INT>:: Iterator J=height.begin (); j!=i;j++)            {                Max_area=max (Max_area,area (j,i));            }        }        return max_area;}    ;


Leetcode | | Container with most water issues

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.