leetcode (7) - a container filled up water

Given n non-negative integers a1, a2, ..., an, a point (i, ai) each represents the number of coordinates. Videos n lines in vertical coordinate, i is a vertical line two end points are (i, AI) and (i, 0). Find out the two lines, which together with the container so that the x-axis configuration can accommodate up water.

Links: https://leetcode-cn.com/problems/container-with-most-water

Problem-solving ideas

From left to start to find the right larger than h_l, find the area
from the right beginning, from the left to find a larger than h_r, find the area

Pruning

  • The height of the outer loop needs to find more and more, the inner loop of the starting point of getting close to the other side
  • Limiting maxA, do, in the outer loop, the inner loop do pruning

Code

class Solution:
    def maxArea(self, height) -> int:
        maxA = 0
        maxl = 0
        begin_r = len(height)-1
        for i in range(len(height)):
            h_l = height[i]
            if h_l> maxl:
                maxl = h_l
            else:
                continue
            if h_l*(begin_r-i)<maxA:
                #break 
                continue
            for j in range(begin_r,i,-1):
                if height[j]>=h_l:
                    begin_r = j
                    maxA = max(maxA,h_l*(j-i))
                    break
                if h_l*(j-i)<=maxA:
                    break
        maxr = 0
        begin_l = 0
        for i in range(len(height)-1,-1,-1):
            h_r = height[i]
            if h_r>maxr:
                maxr = h_r
            else:
                continue
            if h_r*(i-begin_l)<maxA:
                #break 
                continue
            for j in range(begin_l,i):
                if height[j]>=h_r:
                    begin_l = j
                    maxA = max(maxA,h_r*(i-j))
                    break
                if h_r*(i-j)<=maxA:
                    break
        return maxA
#s = Solution()
#print(s.maxArea([5,2,12,1,5,3,4,11,9,4]))

Write your own algorithm should be regarded as the range between the cycle of violence and a double pointer.

To achieve dual-pointer python

class Solution:
    def maxArea(self, height: List[int]) -> int:
        # i为起始长度,j为最长长度,max_area为面积最大值
        i, j, max_area = 0, len(height) - 1, 0
        while i < j:
            if height[i] < height[j]:
                # 长方形的面积为长*较短高度
                max_area = max(max_area, height[i] * (j - i))
                # 长方形的高度向较高方向移动
                i += 1
            else:
                # 长方形的面积为长*较短高度
                max_area = max(max_area, height[j] * (j - i))
                # 长方形的高度向较高方向移动
                j -= 1
        return max_area

Guess you like

Origin www.cnblogs.com/Lzqayx/p/12129585.html