Paint House

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 a n x 3 cost matrix.

  • Time: O(n)
  • Space: O(n)
public int minCost(int[][] costs) {
    int m = costs.length, n = costs[0].length;
    int[][] dp = new int[m][n];
    for (int i = 0; i < n; i++) {
        dp[0][i] = costs[0][i];
    }
    for (int i = 1; i < m; i++) {
        dp[i][0] = costs[i][0] + Math.min(dp[i - 1][1], dp[i - 1][2]);
        dp[i][1] = costs[i][1] + Math.min(dp[i - 1][0], dp[i - 1][2]);
        dp[i][2] = costs[i][2] + Math.min(dp[i - 1][0], dp[i - 1][1]);
    }
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < n; i++) {
        min = Math.min(min, dp[m - 1][i]);
    }
    return min;
}

Paint House II

The cost of painting each house with a certain color is represented by a n x k cost matrix.

  • Time: O(n)
  • Space: O(n)
public int minCost(int[][] costs) {
    int m = costs.length, n = costs[0].length;
    int[][] dp = new int[m][n];
    for (int i = 0; i < n; i++) {
        dp[0][i] = costs[0][i];
    }
    for (int i = 1; i < m; i++) {
        for (int j = 0; j < n; j++) {
            int levelMin = Integer.MAX_VALUE;
            for (int k = 0; k < n && k != j; k++) {
                levelMin = Math.min(levelMin, dp[i - 1][j]);
            }
            dp[i][j] = costs[i][j] + levelMin;
        }
    }
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < n; i++) {
        min = Math.min(min, dp[m - 1][i]);
    }
    return min;
}

results matching ""

    No results matching ""