Container with the most water "Leetcode", Java algorithm, array, max pond water injection

Source: Internet
Author: User

Container with the most water

Given n non-negative integers A1, A2, ..., an, where each represents a point at Coordi Nate (i, ai). N Vertical Lines is drawn such that the the both 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 and n are at least 2.

Given an array of length >2 a[n], where n points are (I,a[i]), finding an area of two points and x-axis lines can fill up the water

Problem Solving Analysis:

1. Water injection is not the largest area, but the shortest plate determines the size of the area

2. Find two shortest plate maximum and two spacing between the largest is the maximum area

Method One:

General idea, take two for loop, traverse all area, take maximum value so your n is too large time space complexity

  • Time complexity:O (n^2)O(N?2??). Calculating area for all\frac{n (n-1)}{2}? 2 ? ? Span class= "Reset-textstyle scriptstyle uncramped mtight" >n (n ? 1) ??  height Pairs.
  • Space complexity: O (1)o(1). Constant extra space is used.

Method Two:

Around two markers to cycle, once the current board is a short board, then move to the other side subscript to find a shorter board

 Public classSolution { Public intMaxarea (int[] height) {        intL=0,r=height.length-1,max=0;  while(l<R) {Max=math.max (Max,math.min (Height[l],height[r]) * (rl)); if(height[l]>Height[r]) {R--; }            ElseL++; }        returnMax; }}
    • Time complexity: o (n)o(n). Single pass.

    • Space complexity: O (1)o(1). Constant space is used.

Container with the most water "Leetcode", Java algorithm, array, max pond water injection

Related Article

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.