Linkedin Interview - Paint House with Colors

1573 단어 interview
There are a row of houses, each house can be painted with three colors red, blue and green. 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. You have to paint the houses with minimum cost. How would you do it? Note: Painting house-1 with red costs different from painting house-2 with red. The costs are different for each house and each color.
 
cost(i,b)=min(cost(i-1,g),cost(i-1,r))+cost of painting i as b; cost(i,g)=min(cost(i-1,b),cost(i-1,r))+cost of painting i as g; cost(i,r)=min(cost(i-1,g),cost(i-1,b))+cost of painting i as r; finally min(cost(N,b),cost(N,g),cost(N,r)) is the ans
 
public static int minCost(int n, int[][] cost) {
	int m = cost.length;
	int[][] f = new int[m][n+1];
	for(int i=1; i<=n; i++) {
		f[0][i] = Math.min(f[1][i-1], f[2][i-1]) + cost[0][i-1];
		f[1][i] = Math.min(f[0][i-1], f[2][i-1]) + cost[1][i-1];
		f[2][i] = Math.min(f[0][i-1], f[1][i-1]) + cost[2][i-1];
	}
	int min = Math.min(Math.min(f[0][n], f[1][n]), f[2][n]);
	return min;
}

public static void main(String[] args) {
	int n = 6;
	int[][] cost = {{7,3,8,6,1,2},{5,6,7,2,4,3},{10,1,4,9,7,6}};
	int min = minCost(n, cost);
	System.out.println(min); // 18
}

 
Reference:
http://www.careercup.com/question?id=9941005

좋은 웹페이지 즐겨찾기