Suppose we have a list of numbers called heights that represents the height of plants and we have another list of values called costs that represents the price needed to increase height of a plant by one. We have to find the smallest cost to make each height in the heights list different from adjacent heights.
So, if the input is like heights = [3, 2, 2] costs = [2, 5, 3], then the output will be 3, as we can increase the last height by 1, which costs 3.
To solve this, we will follow these steps −
Define a function dp() . This will take idx, l_height
if idx is same as size of heights - 1, then
return 0 if heights[idx] is not same as l_height otherwise costs[idx]
ret := inf
for i in range 0 to 2, do
if heights[idx] + i is not same as l_height, then
ret := minimum of ret, dp(idx + 1, heights[idx] + i) + costs[idx] * i
return ret
From the main method return dp(0, null)
Example
Let us see the following implementation to get better understanding −
class Solution: def solve(self, heights, costs): def dp(idx, l_height): if idx == len(heights) - 1: return 0 if heights[idx] != l_height else costs[idx] ret = float("inf") for i in range(3): if heights[idx] + i != l_height: ret = min(ret, dp(idx + 1, heights[idx] + i) + costs[idx] * i) return ret return dp(0, None) ob = Solution() heights = [3, 2, 2] costs = [2, 5, 3] print(ob.solve(heights, costs))
Input
[3, 2, 2], [2, 5, 3]
Output
3