Paint House

medium dp

Problem

There are n houses in a row. Painting each house red, blue, or green has its own cost. No two adjacent houses share a color. Return the minimum total cost.

Inputcosts = [[17,2,17],[16,16,5],[14,3,19]]
Output10
2 + 5 + 3 = 10 (blue → green → blue).

def min_cost(costs):
    r = b = g = 0
    for cr, cb, cg in costs:
        r, b, g = cr + min(b, g), cb + min(r, g), cg + min(r, b)
    return min(r, b, g)
function minCost(costs) {
  let r = 0, b = 0, g = 0;
  for (const [cr, cb, cg] of costs) {
    [r, b, g] = [cr + Math.min(b, g), cb + Math.min(r, g), cg + Math.min(r, b)];
  }
  return Math.min(r, b, g);
}
class Solution {
    public int minCost(int[][] costs) {
        int r = 0, b = 0, g = 0;
        for (int[] c : costs) {
            int nr = c[0] + Math.min(b, g);
            int nb = c[1] + Math.min(r, g);
            int ng = c[2] + Math.min(r, b);
            r = nr; b = nb; g = ng;
        }
        return Math.min(r, Math.min(b, g));
    }
}
int minCost(vector>& costs) {
    int r = 0, b = 0, g = 0;
    for (auto& c : costs) {
        int nr = c[0] + min(b, g);
        int nb = c[1] + min(r, g);
        int ng = c[2] + min(r, b);
        r = nr; b = nb; g = ng;
    }
    return min({r, b, g});
}
Time: O(n) Space: O(1)