5/09/2020

[LeetCode] 11. Container With Most Water

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

This is a typical two pointers problem. Start from the front and rare of the given height array. Since the distance between the 2 vertical lines is decreasing, we need to keep the higher vertical line to get possible larger area.

Time Complexity : O(len(height))
Space Complexity: O(1)

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

No comments:

Post a Comment