Paint House II

hard dp rolling array

Problem

With n houses and k colors and an n×k cost matrix, find the minimum painting cost so that no two adjacent houses share a color. Solve in O(nk).

Inputcosts = [[1,5,3],[2,9,4]]
Output5
1 then 4 = 5 (color 0 then color 2).

def min_cost_ii(costs):
    if not costs: return 0
    k = len(costs[0])
    p1 = p2 = 0
    idx1 = -1
    for row in costs:
        n1 = n2 = float("inf")
        ni1 = -1
        for c in range(k):
            cost = row[c] + (p2 if c == idx1 else p1)
            if cost < n1:
                n2 = n1; n1 = cost; ni1 = c
            elif cost < n2:
                n2 = cost
        p1, p2, idx1 = n1, n2, ni1
    return p1
function minCostII(costs) {
  if (!costs.length) return 0;
  const k = costs[0].length;
  let p1 = 0, p2 = 0, idx1 = -1;
  for (const row of costs) {
    let n1 = Infinity, n2 = Infinity, ni1 = -1;
    for (let c = 0; c < k; c++) {
      const cost = row[c] + (c === idx1 ? p2 : p1);
      if (cost < n1) { n2 = n1; n1 = cost; ni1 = c; }
      else if (cost < n2) n2 = cost;
    }
    p1 = n1; p2 = n2; idx1 = ni1;
  }
  return p1;
}
class Solution {
    public int minCostII(int[][] costs) {
        if (costs.length == 0) return 0;
        int k = costs[0].length, p1 = 0, p2 = 0, idx1 = -1;
        for (int[] row : costs) {
            int n1 = Integer.MAX_VALUE, n2 = Integer.MAX_VALUE, ni1 = -1;
            for (int c = 0; c < k; c++) {
                int cost = row[c] + (c == idx1 ? p2 : p1);
                if (cost < n1) { n2 = n1; n1 = cost; ni1 = c; }
                else if (cost < n2) n2 = cost;
            }
            p1 = n1; p2 = n2; idx1 = ni1;
        }
        return p1;
    }
}
int minCostII(vector>& costs) {
    if (costs.empty()) return 0;
    int k = costs[0].size(), p1 = 0, p2 = 0, idx1 = -1;
    for (auto& row : costs) {
        int n1 = INT_MAX, n2 = INT_MAX, ni1 = -1;
        for (int c = 0; c < k; c++) {
            int cost = row[c] + (c == idx1 ? p2 : p1);
            if (cost < n1) { n2 = n1; n1 = cost; ni1 = c; }
            else if (cost < n2) n2 = cost;
        }
        p1 = n1; p2 = n2; idx1 = ni1;
    }
    return p1;
}
Time: O(nk) Space: O(1)