Skip to Content

Trapping rain water

Home | Coding Interviews | Dynamic Programming | Trapping rain water

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.

#dynamic programming method
class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        if height == []:
            return 0

        n = len(height)
        max_left = [0]* n
        max_right = [0]* n
        ##print(max_left, height)
        max_left[0] = 0
        max_right[n-1] = 0
        for i in range (1, n):
            max_left[i] = max(max_left[i - 1], height[i-1])
             
        for i in range(n-2, -1, -1):
           
            max_right[i] = max(max_right[i + 1], height[i + 1])

        output = 0
        print(max_left, max_right)
        
        for i in range(n):
		    
            lower_boundary = min(max_left[i], max_right[i])
            
            max_trap_at_i = lower_boundary - height[i]
            
            if max_trap_at_i > 0:
                output += max_trap_at_i
                
        return output

Two Pointer method:

class Solution:
    def trap(self, height: List[int]) -> int:
        ans = 0
        l,r = 0 , len(height) -1
        l_max, r_max = 0,0
        while l < r:
		# case 1: lower_bound is from left.
            if height[l] < height[r]:
                if height[l] >= l_max:
                    l_max = height[l]
                else:
                    ans += l_max - height[l]
                l += 1
			# case 2: the lower_bound is from right
            else:
                if height[r] >= r_max:
                    r_max = height[r]
                else:
                    ans += r_max - height[r]
                r -= 1
        return ans

Posted by Jamie Meyer 4 months ago

Related Problems

Given an integer array nums, return the length of the longest strictly increasing subsequence.

You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

Return the maximum coins you can collect by bursting the balloons wisely.

The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).

To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

Return the knight's minimum initial health so that he can rescue the princess.

Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node's values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.