advanced programming techniques hw week8

leetcode #11 Container With Most Water

code show as below:

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        maxWater=0
        i=0
        j=len(height)-1
        while i<j:
            maxWater=max(maxWater,(j-i)*min(height[i],height[j]))
            if height[i]<height[j]:
                i=i+1
            else:
                d=d-1
        return maxWater

Problem solving ideas:

At first, I took it for granted and directly used two loops to exhaust all possibilities to find the maximum value. Then it timed out without a doubt. So I started thinking about algorithms with lower time complexity. Before, it started from the left, fixed one end, and looped the other end to find the maximum value. This is obviously too inefficient, so consider moving both ends at the same time. And because of the two selected lines, the one that can determine the water capacity is the shorter one, so after selecting the two most edge lines in the initial state, you only need to judge the length of the two lines when moving to the middle. Keep the longer line and use a variable to keep track of the maximum amount of water that can be loaded during the move. This movement only guarantees that after each movement, the selection that is more likely to increase the water capacity is taken next, and by comparing the previously recorded maximum value with this value, the one that remains at the end of the cycle is the maximum value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324900797&siteId=291194637