LeetCode Google[02]: Container With Most Water

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

class Solution:
    # Always choose the shorther one to begin. Start from longest width to shortest.
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height)-1
        max_area = 0
        while left < right:
            width = right - left
            area = min(height[left], height[right])*width
            if area > max_area:
                max_area = area
            start_from = ''
            candidte = 0
            if height[left] < height[right]:
                start_from = 'left' 
            else:
                start_from = 'right'
                
            if start_from == 'left':
                i = left
                while height[i] <= height[left] and i < len(height) - 1:
                    i += 1      
                left = i
            else:
                i = right
                while height[i] <= height[right] and i > 0:
                    i -= 1 
                right = i
        return max_area

猜你喜欢

转载自www.cnblogs.com/lywangjapan/p/12430228.html
今日推荐