Description

There are a row ofnhouses, each house can be painted with one of thekcolors. 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 anxkcost matrix. For example,costs[0][0]is the cost of painting house0with color0;costs[1][2]is the cost of painting house1with color2, and so on... Find the minimum cost to paint all houses.

Example

Givenn= 3,k= 3,costs=[[14,2,11],[11,14,5],[14,3,10]]return10

house 0 is color 2, house 1 is color 3, house 2 is color 2,2 + 5 + 3 = 10

Solution
public class Solution {
    /**
     * @param costs n x k cost matrix
     * @return an integer, the minimum cost to paint all houses
     */
    public int minCostII(int[][] costs) {
        // Write your code here
        if (costs == null || costs.length == 0 || costs[0] == null || costs[0].length == 0) {
            return 0;
        }

        int min = 0;
        int secondMin = 0;
        int minIndex = 0;
        for (int i = 0; i < costs.length; i++) {
            int curMin = Integer.MAX_VALUE;
            int curSecondMin = Integer.MAX_VALUE;
            int curMinIndex = 0;
            for (int j = 0; j < costs[0].length; j++) {
                costs[i][j] += j == minIndex ? secondMin : min;
                if (costs[i][j] <= curMin) {
                    curSecondMin = curMin;
                    curMin = costs[i][j];
                    curMinIndex = j;
                } else if (costs[i][j] <= curSecondMin) {
                    curSecondMin = costs[i][j];
                }
            }

            min = curMin;
            secondMin = curSecondMin;
            minIndex = curMinIndex;
        }

        return min;
    }
}

results matching ""

    No results matching ""