Leetcode container with most water

Source: Internet
Author: User

GivenNNon-negative integersA1,A2,...,An, Where each represents a point at coordinate (I,AI).NVertical lines are drawn such that the two endpoints of LineIIs (I,AI) And (I, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.

 

There are N points (I, AI) in the two-dimensional coordinate system. AI> = 0. There are n vertical lines from (I, AI) to (I, 0.
Find two vertical lines to maximize the area of the rectangle they constitute. The height of the rectangle depends on the shortest vertical line.
Idea: greedy
Scanning starts from the beginning and end of two subscripts head and trail, and maintains the largest rectangular area with one variable maxarea.
If the head points to a vertical line shorter than the trail, move the head right
Otherwise, move trail to the left.
Calculate the area and update maxarea
Complexity: time O (N), Space O (1)

 

public class Solution {    public int maxArea(int[] height) {        if (height.length<2) {            return 0;        }                int leftEdge=0;        int rightEdge=height.length-1;        int maxarea=0,area=0;        while (leftEdge!=rightEdge) {                area=Math.min(height[leftEdge], height[rightEdge])*(rightEdge-leftEdge);                if (area>maxarea) {                    maxarea=area;                }                if (height[leftEdge]

 

Leetcode 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.