배열 추가문제2

less than 1 minute read

Question 1: Container With Most Water

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

입력: height = [1,8,6,2,5,4,8,3,7]

출력: 49

내 풀이

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        distance = len(height) - 1    
        max_volume = 0
        
        for d in range(distance, 0, -1):
            if height[left] < height[right]:
                max_volume = max(height[left] * d, max_volume)
                left += 1
            else:
                max_volume = max(height[right] * d, max_volume)
                right -= 1
        
        return max_volume
  • 왼쪽 기둥과 오른쪽 기둥을 하나씩 비교해가며 낮은 높이의 기둥을 기둥사이의 거리만큼을 곱한 값을 max_volume으로 정의하였다.

결과

Runtime: 1016 ms, faster than 40.47% of Python3 online submissions for Container With Most Water. Memory Usage: 27.5 MB, less than 57.49% of Python3 online submissions for Container With Most Water.


Comments