Painting the Walls Problem
#2742
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2742.
You are given two 0-indexed integer arrays, cost and time, of size n representing the costs and the time taken to paint n different walls respectively. There are two painters available:
- A paid painter that paints the
i^thwall intime[i]units of time and takescost[i]units of money. - A free painter that paints any wall in
1unit of time at a cost of0. But the free painter can only be used if the paid painter is already occupied.
Return the minimum amount of money required to paint the n walls.
Example 1:
Input: cost = [1,2,3,2], time = [1,2,3,2]
Output: 3
Explanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
Example 2:
Input: cost = [2,3,4,2], time = [1,1,1,1]
Output: 4
Explanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
Constraints:
1 <= cost.length <= 500cost.length == time.length1 <= cost[i] <= 10^61 <= time[i] <= 500
Solution
Approach: Memoized search
For each wall, either the paid painter paints it or the free painter does. Define dfs(i, j) as the minimum cost to finish walls i..n-1 when the free painter still has j units of time banked from earlier walls. The answer is dfs(0, 0).
- If
n - i <= j, the free painter can paint all remaining walls: cost0. - If
i >= n(and the first case did not apply), the state is impossible: infinity. - Otherwise take the cheaper of two choices: hire the paid painter,
cost[i] + dfs(i + 1, j + time[i]), or leave the wall to the free painter,dfs(i + 1, j - 1).
j can go negative, so languages with array memo tables shift it by n to keep the index in [0, 2n].
Complexity: O(n^2) time and space.
from functools import lru_cache
from math import inf
class Solution:
def paintWalls(self, cost: List[int], time: List[int]) -> int:
@lru_cache(None)
def dfs(i: int, j: int) -> int:
if n - i <= j:
return 0
if i >= n:
return inf
return min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1))
n = len(cost)
return dfs(0, 0)