[Leetcode] [Java] Container with most water

Source: Internet
Author: User

Title:

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.


Test Instructions:

A given n non-negative integera1 , a2 , ..., an , each delegate in the coordinate(I, ai ) on the point where the connection(I, ai ) and (I, 0) to form n vertical lines. Find two vertical lines, and x coordinates to form a container, so that this container contains the most water.

Note: You can not tilt the container.

Algorithm Analysis:


Strategies for both sides of the clip


Two indicators I J go in the middle. Each time the area between I and J is calculated, if it is larger than the current maximum area, the maximum area is updated, otherwise the indicator of the smaller number of the two moves forward.


If Height[i] <= height[j], then i++, because here Height[i] is the bottleneck, J moving in will only reduce the area, no more areas.


This is a greedy strategy, each time to take the shortest side of the fence to advance, hoping to get more water.


AC Code:

    public  int Maxarea (int[] height)     {    int left=0;    int right=height.length-1;    int temwater;    int res=0;    while (Left<right)    {    temwater=math.min (Height[left], height[right]) * (right-left);    if (temwater>res) res=temwater;    if (Height[left]


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] Container with 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.