BiruLyu
7/8/2017 - 4:52 PM

265. Paint House II(O(n*k*k)).java

public class Solution {
    public int minCostII(int[][] costs) {
        if (costs == null || costs.length < 1) return 0;
        int n = costs.length;
        int k = costs[0].length;
        
        int prevMin = 0, prevSecMin = 0, preMinInd = -1;
        for (int i = 0; i < n; i++) {
            int curMin = Integer.MAX_VALUE;
            int curSecMin = Integer.MAX_VALUE;
            int curMinInd = -1;
            for (int j = 0; j < k; j++) {
                int val = costs[i][j] + (j == preMinInd ? prevSecMin : prevMin);
                if (curMinInd < 0) { // initialize curMin
                    curMin = val;
                    curMinInd = j;
                } else if (val < curMin) { // update curMin
                    curSecMin = curMin;
                    curMin = val;
                    curMinInd = j;
                } else if (val < curSecMin) { // //when curMin <= val< curSecMin, update curSecMin
                    curSecMin = val;
                }
            }
            prevMin = curMin;
            prevSecMin = curSecMin;
            preMinInd = curMinInd;
        }
        return prevMin;
    }
}
public class Solution {
    public int minCostII(int[][] costs) {
        if (costs == null || costs.length == 0 || costs[0].length == 0) {
            return 0;
        }
        for (int i = 1; i < costs.length; i++) {
            for (int j = 0; j < costs[0].length; j++) {
                int min = Integer.MAX_VALUE;
                for (int k = 0; k < costs[0].length; k++) {
                    if (j == k) {
                        continue;
                    }
                    min = Math.min(min, costs[i - 1][k]);
                }
                costs[i][j] += min;
            }
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < costs[0].length; i++) {
            min = Math.min(min, costs[costs.length - 1][i]);
        }
        return min;
    }
}