물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

42. Trapping Rain Water

BEstyle 2023. 1. 10. 02:56

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:
    
    def trap(self, height: List[int]) -> int:
        lmax = [0] * len(height)
        rmax = [0] * len(height)
        clmax = 0
        crmax=0
        for i in range(len(height)-1):
            lmax[i+1] = clmax = max(clmax,height[i])
            rmax[i+1] = crmax = max(crmax,height[-1-i])
        rmax = rmax[::-1]
        for i in range(len(height)):
            height[i] = max(min(lmax[i],rmax[i])-height[i], 0 )
        return sum(height)

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

283. Move Zeroes  (0) 2023.01.10
15. 3Sum  (0) 2023.01.10
1637. Widest Vertical Area Between Two Points Containing No Points  (0) 2022.12.30
1874. Minimize Product Sum of Two Arrays  (0) 2022.12.30
21. Merge Two Sorted Lists  (0) 2022.12.29