Two Pointer [리트코드] 42. Trapping Rain Water

이영준·2022년 9월 22일
0

알고리즘 문제풀이

목록 보기
6/24
from typing import List


class Solution:
    def trap(self, height: List[int]) -> int:

        while height[0] == 0 and len(height) > 1:
            height = height[1:]
        while height[-1] == 0 and len(height) > 1:
            height = height[:-1]

        volume = 0
        sorted_height = sorted(height)
        max_height = sorted_height[-1]
        left_current_max = height[0]
        right_current_max = height[-1]
        left_index = 0
        right_index = len(height)-1

        while left_index <= right_index:
            #print('current indexes are', left_index, right_index)
            while height[left_index] != max_height and left_index <= right_index:
                if height[left_index] <= left_current_max:
                    volume += left_current_max-height[left_index]
                    #print("found left max volume is", volume)
                else:
                    left_current_max = height[left_index]
                left_index += 1
                # print('left index to', left_index)
            while height[right_index] != max_height and left_index <= right_index:
                if height[right_index] <= right_current_max:
                    volume += right_current_max-height[right_index]
                    #print("found right max volume is", volume)
                else:
                    right_current_max = height[right_index]
                right_index -= 1
                # print('right index to', right_index)
            left_current_max, right_current_max = max_height, max_height
            left_index += 1
            right_index -= 1

        return volume


solution = Solution()
print(Solution.trap(solution,
                    [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]))
profile
컴퓨터와 교육 그사이 어딘가

0개의 댓글