HardNo. 2742

Painting the Walls — LeetCode 2742 Python Solution

Topics
Array, Dynamic Programming
Reading time
3 min

The problem

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 ith wall in time[i] units of time and takes cost[i] units of money.

Example

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.

Python solution

PythonSolution
class Solution:
    def paintWalls(self, cost: List[int], time: List[int]) -> int:
        @cache
        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)

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2742. Painting the Walls is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2741Special PermutationsMedium
2746Decremental String ConcatenationMedium
2750Ways to Split Array Into Good SubarraysMedium
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium

Frequently asked questions

How hard is LeetCode 2742. Painting the Walls?

LeetCode 2742. Painting the Walls is rated Hard on LeetCode.

What topics does LeetCode 2742. Painting the Walls cover?

LeetCode 2742. Painting the Walls is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.