Container with most Water--leetcode

Source: Internet
Author: User

Topic:

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.

idea: If the simplest way is to use brute force search, squared time complexity, but you can also use a simple method

Next we'll consider how to optimize. The idea is somewhat similar to the two Sum The second method of--clamp force. From the end of the array, each iteration to determine the number of left pointer and right pointer pointing to which large, if the left pointer small, meaning that the left to move right pointer is not possible to make the result better, because the bottleneck in the left pointer, moving right pointer will only be smaller, So this time we choose left pointer to move right. Conversely, the right pointer is selected to move left. In this process has been to maintain the largest volume. The code is as follows:

#include <iostream> #include <vector> #include <string> #include <stack>using namespace std;/*      Can fit up to water */int area (vector<int> &height, int i, int j) {int h = height[i]

Container with most Water--leetcode

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.