(Leetcode 11). Containers with the most water

Source: Internet
Author: User

Given n nonnegative integers a1, a 2, ...,aN, each number represents a point in the coordinate (i, ai). In the coordinates, draw n vertical lines, the two endpoints of the vertical line i are (i, ai) and (I, 0) respectively. Find two of these lines so that they can hold the largest amount of water in a container that is combined with the x -axis.

Description: You cannot tilt the container, and the value of N is at least 2.

The vertical line in the figure represents the input array [1,8,6,2,5,4,8,3,7]. In this case, the maximum value for the container to hold water (expressed as a blue part) is 49.


Input: [1,8,6,2,5,4,8,3,7] Output: 49

Solution: Approximation method
Each time left and right, the short end is gone.
If you select the short end "s= is less than or equal to the current maximum interval length", the most area is also the leftmost and most right rectangle, so it is no longer necessary to consider the short end, the immediate approximation.

Just started to get into one-way thinking, although there is optimization (find i+1~n between the maximum subscript K, then i~[i+1, K] The maximum area is certainly (I, K)), but time consumption more than 80 times times.
Optimal solution: Approximation method, approaching from both ends to the middle, and cutting off the leftmost/right end.
How to do the best:
1. Conversion thinking, from one-way to multi-directional, reverse;
2. Consider the critical conditions of both ends and boundaries;

(Leetcode 11). Containers with the 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.