11. Container With Most Water

# Medium

Two pointers.

Left pointer and right pointer to make sliding window. Keep maximum area in record, and move left or right pointer to ensure both of them are the longest vertical lines, compute the temporary area to be temp.

Solution

  1. Keep maxium area in record.

  2. Move left or right pointer each time by finding the longest two lines.

简单来说,有两种可能性能找到最大值,第一种距离尽量最远的两个垂线,第二种高度尽量最高的两条垂线。

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        start = 0
        end = len(height) - 1
        area = 0
        while start < end:
            temp = min(height[start], height[end]) * (end-start)
            area = max(area, temp)
            if height[start] < height[end]:
                start += 1
            else:
                end -= 1
                
        return area

Time complexity = O(n)O(n) , space complexity = O(1)O(1)

Last updated