Dynamic Programming
Paint House
DESCRIPTION (credit Leetcode.com)
You have a row of n houses along a street, and each house needs to be painted with one of three colors: Red, Blue, or Green. The painting costs vary for each house and color combination, given in a 2D array costs where:
- costs[i][0] = cost to paint house i Red
- costs[i][1] = cost to paint house i Blue
- costs[i][2] = cost to paint house i Green
There's one constraint: to keep the neighborhood visually appealing, no two adjacent houses can share the same color.
Write a function to return the minimum total cost to paint all houses.
Example 1
Input:
costs = [[17, 2, 17], [16, 16, 5], [14, 3, 19]]
Output:
10
Explanation:
- Paint house 0 Blue (cost = 2)
- Paint house 1 Green (cost = 5)
- Paint house 2 Blue (cost = 3)
- Total = 2 + 5 + 3 = 10
Example 2
Input:
costs = [[7, 6, 2]]
Output:
2
Explanation: With a single house, pick the cheapest color (Green at cost 2).
Example 3
Input:
costs = [[3, 5, 3], [6, 17, 6], [7, 13, 18], [9, 10, 18]]
Output:
26
Explanation
Defining the State
- dp[i][0] = minimum cost to paint houses 0 to i, where house i is painted Red
- dp[i][1] = minimum cost to paint houses 0 to i, where house i is painted Blue
- dp[i][2] = minimum cost to paint houses 0 to i, where house i is painted Green
The Recurrence Relation
- House i - 1 must be either Blue or Green
- So dp[i][0] = costs[i][0] + min(dp[i-1][1], dp[i-1][2])
dp[i][0] = costs[i][0] + min(dp[i-1][1], dp[i-1][2]) # Paint house i Red
dp[i][1] = costs[i][1] + min(dp[i-1][0], dp[i-1][2]) # Paint house i Blue
dp[i][2] = costs[i][2] + min(dp[i-1][0], dp[i-1][1]) # Paint house i GreenBase Case
dp[0][0] = costs[0][0] # Cost to paint house 0 Red
dp[0][1] = costs[0][1] # Cost to paint house 0 Blue
dp[0][2] = costs[0][2] # Cost to paint house 0 GreenWalkthrough Example
- Red: 17, Blue: 2, Green: 17
- Red: 16 + min(2, 17) = 16 + 2 = 18
- Blue: 16 + min(17, 17) = 16 + 17 = 33
- Green: 5 + min(17, 2) = 5 + 2 = 7
- Red: 14 + min(33, 7) = 14 + 7 = 21
- Blue: 3 + min(18, 7) = 3 + 7 = 10
- Green: 19 + min(18, 33) = 19 + 18 = 37
paint house - 2D DP approach
0 / 11
Space Optimization
Solution
paint house
0 / 12
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n) where n is the number of houses. We iterate through each house exactly once, and at each house we do constant work (comparing 2 values and adding).
Space Complexity: O(1) The space-optimized solution uses only 3 variables instead of a 2D array. The 2D table approach would use O(n) space.