"Leetcode" Container with the most water problem solving report

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.

Resolution

Test instructions: In a two-dimensional coordinate system, (I, AI) represents a segment from (I, 0) to (i, AI), and any two of such segments and X-axes make up a cask to find the cask that can hold the most water and return its volume.

Two-tier for-loop violence will time out, so abandon this lazy idea as soon as possible.

Is there an O (n) solution?

The answer is, with two pointers from both ends to the middle, if the left side of the short less right operand end, then right shift, and the right side of the left shift, know that both ends move to the middle of the overlap, recording the process of each composition of the volume of barrels, return the largest. (Think about why this is reasonable?) )

public class Solution {public    int maxarea (int[] height) {        if (Height.length < 2) return 0;        int ans = 0;        int l = 0;        int r = height.length-1;        while (L < r) {            int v = (r-l) * Math.min (Height[l], height[r]);            if (V > ans) ans = v;            if (Height[l] < height[r]) l++;            else r--;        }        return ans;    }}

Rationality explanation: When the left segment L is less than the right end segment R, we move the l to the right, then discard the L and the right end of the other segments (R-1, R-2, ...) Wooden barrels, these barrels are not necessary to judge, because the volume of these barrels is certainly not a large volume of barrels of L and R.


"Leetcode" Container with the most water problem solving report

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.