HardNo. 0265LeetCode Premium
Paint House II — LeetCode 265 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Array, Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0045 | Jump Game II | Medium |
| 0053 | Maximum Subarray | Medium |
| 0055 | Jump Game | Medium |
| 0063 | Unique Paths II | Medium |
| 0064 | Minimum Path Sum | Medium |
| 0085 | Maximal Rectangle | Hard |
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.