Dynamic Programming
Paint House II
DESCRIPTION (credit Leetcode.com)
You have a row of n houses along a street, and each house needs to be painted with one of k colors. The painting costs vary for each house and color combination, given in a 2D array costs where:
- costs[i][j] = cost to paint house i with color j
There's one constraint: no two adjacent houses can share the same color.
Write a function to return the minimum total cost to paint all houses.
Follow-up: Can you solve it in O(n × k) time instead of the naive O(n × k²) approach?
Example 1
Input:
costs = [[1, 5, 3], [2, 9, 4]]
Output:
5
Explanation:
- Paint house 0 with color 0 (cost = 1)
- Paint house 1 with color 2 (cost = 4)
- Total = 1 + 4 = 5
Example 2
Input:
costs = [[1, 3], [2, 4]]
Output:
5
Explanation: Paint house 0 with color 0 (cost = 1), house 1 with color 1 (cost = 4). Total = 5.
Explanation
The Naive Approach
- dp[i][j] = minimum cost to paint houses 0 to i, where house i is painted with color j
dp[i][j] = costs[i][j] + min(dp[i-1][m] for all m != j)The Key Optimization
- min1: The smallest value in the previous row
- min2: The second smallest value in the previous row
- min1Idx: The index of min1
Walkthrough Example
- prev = [1, 5, 3]
- min1 = 1 (at index 0), min2 = 3
- j=0: Can't use min1 (same index), so use min2: 2 + 3 = 5
- j=1: Use min1: 9 + 1 = 10
- j=2: Use min1: 4 + 1 = 5
- prev = [5, 10, 5]
- New min1 = 5 (at index 0), min2 = 5
- j=0: Can't use min1: 8 + 5 = 13
- j=1: Use min1: 1 + 5 = 6
- j=2: Use min1: 6 + 5 = 11
- prev = [13, 6, 11]
- New min1 = 6 (at index 1), min2 = 11
- j=0: Use min1: 4 + 6 = 10
- j=1: Can't use min1: 2 + 11 = 13
- j=2: Use min1: 3 + 6 = 9
- prev = [10, 13, 9]
Visualization
paint house II
0 / 20
Solution
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n × k) where n is the number of houses and k is the number of colors. We iterate through each house once, and for each house we do O(k) work to find min1/min2 and compute the new row.
Space Complexity: O(k) We only store the previous row's values (length k) instead of the full n × k table.