MediumNo. 0256LeetCode Premium

Paint House — LeetCode 256 Python Solution

Topics
Array, Dynamic Programming
Reading time
2 min

The problem

There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different.

Example

Input
costs = [[17,2,17],[16,16,5],[14,3,19]]
Output
10
Explanation
Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.

Python solution

PythonSolution
class Solution:
    def minCost(self, costs: List[List[int]]) -> int:
        a = b = c = 0
        for ca, cb, cc in costs:
            a, b, c = min(b, c) + ca, min(a, c) + cb, min(a, b) + cc
        return min(a, b, c)

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 256. Paint House 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
1473Paint House IIIHard
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium

Frequently asked questions

How hard is LeetCode 256. Paint House?

LeetCode 256. Paint House is rated Medium on LeetCode.

What topics does LeetCode 256. Paint House cover?

LeetCode 256. Paint House is tagged Array and Dynamic Programming on LeetCode.

Is LeetCode 256. Paint House a premium problem?

Yes. LeetCode 256. Paint House 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.