[leetcode] 42. Trapping Rain Water

2022. 11. 2. 09:37노트/Algorithm : 알고리즘

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

 

 

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

 

Constraints:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

 

class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left, right = 0, len(height)-1
        volumne_list = [] 
        stop_point = height.index(max(height))
        
        left_max, right_max = height[left] , height[right]
        while left < stop_point: 
            if height[left] >= left_max:
                left_max = height[left]
            
            volumne = left_max - height[left]
            volumne_list.append(volumne)
            left += 1
            
        while stop_point < right:
            if height[right] >= right_max:
                right_max = height[right]
                
            volumne = right_max - height[right]
            volumne_list.append(volumne)
            right -= 1 
        
        return sum(volumne_list)

'노트 > Algorithm : 알고리즘' 카테고리의 다른 글

[leetcode] 561. Array Partition  (0) 2022.11.04
[leetcode] 15. 3Sum  (0) 2022.11.03
리스트에서 최솟값 찾기 구현  (0) 2021.08.11
[leetcode] 21. Merge Two Sorted Lists  (0) 2021.08.10
[leetcode] 20. Valid Parentheses  (0) 2021.08.10