[Algorithm brush question] The container that holds the most water

Problem: 11. The container that holds the most water

insert image description here

train of thought

At the beginning, I only thought about violence, and the idea was similar to the idea of ​​the longest palindrome in the existing string, locating the start and end marks of a string.
But after submitting it, I found that it timed out. The main reason is that the restriction conditions are difficult to write, so double pointers should be considered for optimization.

problem solving method

In each state, no matter whether the long board or the short board is narrowed to the middle, the width of the bottom edge of the tank will be shortened by −1-1−1​:
If the short board is moved inward, the short board of the tank will be min(h[ i],h[j])min(h[i], h[j])min(h[i],h[j]) may become larger, so the area of ​​the next sink may increase.
If the long board is moved inward, the short board of the tank min(h[i],h[j])min(h[i], h[j])min(h[i],h[j])​ remains unchanged Or become smaller, so the area of ​​the next sink must become smaller.
Therefore, initialize the two pointers to arrange the left and right ends of the water tank, move the short board inward by one frame each cycle, and update the maximum area until the two pointers meet and jump out; the maximum area can be obtained.

the complexity

  • time complexity:

Add time complexity, example: O ( N ) O(N)O ( N )

  • Space complexity:

Add space complexity, example: O ( 1 ) O(1)O(1)

Code


class Solution:
    def maxArea(self, height: List[int]) -> int:
        start = 0 
        end = len(height) - 1
        res = 0

        while start < end:
            if height[start] < height[end]:
                res = max(res,height[start] * (end-start))
                start = start + 1
            else:
                res = max(res,height[end] * (end-start))
                end = end - 1
        return res 

But at the beginning, the submission was done with the idea of ​​​​the longest palindrome in the string, and the timeout was always reported, but it is not difficult to implement.

Code (no optimization)

	class Solution:
    def maxArea(self, height: List[int]) -> int:
        max_vol = 0
        flag_start = 0

        start_index = 0
        while start_index < len(height):
            if height[start_index] < height[flag_start]:
                pass
            else:
                for i in range(start_index+1,len(height))[::-1]:
                    wid_ = i - start_index
                    hei_ = min(height[i],height[start_index])
                    vol = wid_ * hei_
                    if vol > max_vol:
                        max_vol = vol
                        flag_start = start_index

            start_index = start_index + 1
        return max_vol

Guess you like

Origin blog.csdn.net/qq_27180763/article/details/129472586