HardNo. 0265LeetCode Premium

Paint House II — LeetCode 265 Python Solution

Topics
Array, Dynamic Programming
Reading time
2 min

The problem

There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different.

Example

Input
costs = [[1,5,3],[2,9,4]]
Output
5
Explanation
Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;

Python solution

PythonSolution
class Solution:
    def minCostII(self, costs: List[List[int]]) -> int:
        n, k = len(costs), len(costs[0])
        f = costs[0][:]
        for i in range(1, n):
            g = costs[i][:]
            for j in range(k):
                t = min(f[h] for h in range(k) if h != j)
                g[j] += t
            f = g
        return min(f)

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 265. Paint House II 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
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard

Frequently asked questions

How hard is LeetCode 265. Paint House II?

LeetCode 265. Paint House II is rated Hard on LeetCode.

What topics does LeetCode 265. Paint House II cover?

LeetCode 265. Paint House II is tagged Array and Dynamic Programming on LeetCode.

Is LeetCode 265. Paint House II a premium problem?

Yes. LeetCode 265. Paint House II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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.