14.17 Paint House
14.17.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 256
- Difficulty: Easy
- URL: https://leetcode.com/problems/lc-paint-house/
- Tags:
- Techniques: Dynamic Programming, Tabulation, Array
14.17.2 Description
You are given an n x 3 matrix costs where costs[i][j] denotes the cost of painting house i with color j. Adjacent houses must not share a color. Return the minimum total cost to paint all houses.
14.17.5 Solution - Rolling DP
14.17.5.1 Walkthrough
Keep three running totals for the cost of painting up to the current house when the current house ends in red, green, or blue. For house i, the red cost equals costs[i][0] + min(previousGreen, previousBlue), and similarly for the other colors. Update the running totals and take the minimum at the end.
14.17.5.3 Implementation Steps
- Initialize
red = green = blue = 0. - For each house:
- Compute new totals for each color by adding its cost to the minimum of the other two previous totals.
- Update
red,green,blueto these new totals.
- Return
min(red, green, blue).
14.17.5.4 Code - Java
public int minCost(int[][] costs) {
int red = 0, green = 0, blue = 0;
for (int[] cost : costs) {
int newRed = cost[0] + Math.min(green, blue);
int newGreen = cost[1] + Math.min(red, blue);
int newBlue = cost[2] + Math.min(red, green);
red = newRed;
green = newGreen;
blue = newBlue;
}
return Math.min(red, Math.min(green, blue));
}