Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int minCostPaintAtMostTwoSameColor(int[][] cost)
- {
- // cost in form n x 3
- // cost[0][1] = paint house 0 with color 1
- int n = cost.length, inf = Integer.MAX_VALUE;
- // f[i][j] = minimum cost to paint up to i houses ending with paint j
- int[][] f = new int[n + 1][3];
- f[1] = cost[0];
- for(int j = 0; j < 3; j++)
- f[2][j] = Math.min(f[1][0], Math.min(f[1][1], f[1][2])) + cost[1][j];
- for(int i = 2; i < n; i++)
- {
- // loop through colors
- for(int j = 0; j < 3; j++)
- {
- int diffColor = inf, sameColor = inf;
- for(int k = 0; j < 3; k++)
- {
- if(j == k) continue;
- diffColor = Math.min(diffColor, f[i][k]);
- sameColor = Math.min(sameColor, f[i - 1][k] + cost[i][j]);
- }
- f[i + 1][j] = Math.min(diffColor, sameColor);
- }
- }
- return Math.min(Math.min(f[n][0], f[n][1]), f[n][2]);
- }
- int minCostPaintNoSameColor(int[][] cost)
- {
- int n = cost.length, inf = Integer.MAX_VALUE;
- int[][] f = new int[n + 1][3];
- for(int i = 0; i < n; i++)
- {
- f[i + 1][0] = Math.min(f[i][1], f[i][2]) + cost[i][0];
- f[i + 1][1] = Math.min(f[i][0], f[i][2]) + cost[i][1];
- f[i + 1][2] = Math.min(f[i][0], f[i][1]) + cost[i][2];
- }
- return Math.min(Math.min(f[n][0], f[n][1]), f[n][2]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement