Walls Coloring II
JavaView on GFG
Advertisement
Intuition
Color n walls with k colors minimizing cost where adjacent walls must differ. DP.
Algorithm
- 1dp[i][c] = min cost to color walls 1..i with wall i colored c. Transition: min over all c != prev_c.
Common Pitfalls
- •O(nk^2) naive. Optimize to O(nk) by tracking min and second-min of previous row.
Walls Coloring II.java
Java
// Approach: DP. dp[i][c] = min cost to paint wall i with color c, considering the k-window constraint.
// Time: O(n * colors) Space: O(n)
class Solution {
int minCost(int[][] costs) {
int n = costs.length;
int k = costs[0].length;
if (k == 1 && n == 1)
return costs[0][0];
if (k <= 1 || n == 0)
return -1;
int min = 0, secondMin = -1;
int minVal = costs[0][0], secondMinVal = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (i != 0) {
for (int j = 0; j < k; j++)
costs[i][j] += costs[i - 1][j];
}
min = 0;
secondMin = -1;
minVal = costs[i][0];
secondMinVal = Integer.MAX_VALUE;
// find min and second min
for (int j = 1; j < k; j++) {
if (costs[i][j] < minVal) {
secondMin = min;
secondMinVal = minVal;
min = j;
minVal = costs[i][j];
} else if (j != min && (secondMin == -1 || costs[i][j] < secondMinVal)) {
secondMin = j;
secondMinVal = costs[i][j];
}
}
for (int j = 0; j < k; j++) {
if (j != min)
costs[i][j] = minVal;
else
costs[i][j] = secondMinVal;
}
}
return minVal;
}
}Advertisement
Was this solution helpful?