欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linkedin Interview - Paint House with Colors

程序员文章站 2024-01-18 09:39:58
...

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