Paint House - 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. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs. For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on.

Return the minimum cost to paint all houses.

Input & Output

Example 1 — Basic Three Houses
$ Input: costs = [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
💡 Note: Paint house 0 blue (cost 2), house 1 green (cost 5), house 2 blue (cost 3). Total cost = 2 + 5 + 3 = 10.
Example 2 — Single House
$ Input: costs = [[7,6,2]]
Output: 2
💡 Note: Only one house, so paint it with the cheapest color (green, cost 2).
Example 3 — Two Houses
$ Input: costs = [[5,8,6],[19,14,13]]
Output: 18
💡 Note: Paint house 0 red (cost 5), house 1 green (cost 13). Total cost = 5 + 13 = 18.

Constraints

  • 1 ≤ costs.length ≤ 100
  • costs[i].length == 3
  • 1 ≤ costs[i][j] ≤ 20

Visualization

Tap to expand
Paint House - Dynamic Programming INPUT 3 Houses to Paint House 0 House 1 House 2 Cost Matrix (n x 3) Red Blue Green 17 2 17 H0 16 16 5 H1 14 3 19 H2 costs=[[17,2,17],[16,16,5],[14,3,19]] ALGORITHM STEPS 1 Initialize DP dp[0] = costs[0] 2 Recurrence dp[i][c] = cost[i][c] + min(dp[i-1][other colors]) 3 Fill DP Table Process each house R B G H0: 17 2 17 H1: 18 33 7 H2: 21 10 37 4 Return Min min(dp[n-1]) = min(21,10,37) FINAL RESULT Optimal Color Assignment Blue: 2 Green: 5 Blue: 3 Cost Breakdown House 0 (Blue): 2 House 1 (Green): 5 House 2 (Blue): 3 Output: 10 Minimum Total Cost OK - No adjacent houses have same color! Key Insight: For each house, we only need to track the minimum cost to paint it each color. When painting house i with color c, we add cost[i][c] to the minimum of painting house i-1 with the OTHER two colors. Time: O(n), Space: O(1) - only need previous row's values! TutorialsPoint - Paint House | Dynamic Programming Approach
Asked in
Facebook 45 Amazon 35 Google 30 Microsoft 25
89.6K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen