A container with the most water per day (leetcode) (double pointer)

Container with the most water (double pointer)

11. Container with the most water

Medium difficulty 1342 Collection sharing Switch to English Follow feedback

You are given n non-negative integers a 1, a 2, ..., an , each number represents a point ( i , ai ) in coordinates . Draw n vertical lines in the coordinates. The two endpoints of the vertical line i are ( i , ai ) and ( i , 0). Find two of the lines so that the container they form with the x- axis can hold the most water.

Note: You cannot tilt the container, and the value of n is at least 2.

img

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 that the container can hold water (represented by the blue part) is 49.

Examples:

输入:[1,8,6,2,5,4,8,3,7]
输出:49

answer:

class Solution:
    def maxArea(self, height: List[int]):
        vol=0
        leng=len(height)
        l,r=height[0],height[leng-1]
        nl,nr=0,leng-1
        for i in range(leng-1):
            mi=min(l, r)
            vol = max(mi*(leng-i-1),vol)
            if mi==l:
                nl+=1
                l=height[nl]
            else:
                nr-=1
                r=height[nr]
        return(vol)

Resolution practice:

After reading the question, the first thing I thought of was the double loop, but it felt very troublesome, so I set a different course. I may have done such a question or have been taught in an algorithm class before, and I always feel a little impressed.

I thought of moving on both sides, just selecting a small side to move, so the correct way is him ,,,, double pointer

Define two boundary variables r and l, and the cycle moves to the middle. In the process, compare the two volumes vol and select a large value and then assign it to vol. The boundary is updated after each cycle.

As for why you want to move the small side, please see here

image-20200418164303414

Guess you like

Origin www.cnblogs.com/rower/p/12726652.html