Intuition
Pre-cost every substring to a semi-palindrome, then split the string into k parts with a dynamic program that reuses the best split of the prefix.
Explanation
Idea
Two tables drive the answer.
1. Cost table. cost[i][j] is the fewest letter changes to turn the substring s[i..j] into a semi-palindrome. For a substring of length L, try every divisor d with 1 <= d < L and L % d == 0. Characters that share the same remainder modulo d form one group; within a group the characters must read the same forwards and backwards, so pair the first with the last, the second with the second-last, and count every mismatched pair. The cheapest divisor wins.
2. Partition DP. dp[i][j] is the minimum changes to split the first i characters of s into j semi-palindrome parts. Because a semi-palindrome needs a divisor strictly smaller than its length, every part is at least two characters long. Fix where the last part begins at index p:
dp[i][j] = min over p of ( dp[p][j-1] + cost[p][i-1] ), for p from 2*(j-1) to i-2.
Seed dp[0][0] = 0 and return dp[n][k].
Worked example
s = "abcac", k = 2.
cost[0][1]for"ab": only divisor isd = 1, one group"ab";a != b, so 1 change.cost[2][4]for"cac":d = 1, group"cac";c == c, middle free, so 0 changes.
The DP tries splitting after index 1: first part "ab" (cost 1) + second part "cac" (cost 0) = 1. Every other split costs at least as much, so dp[5][2] = 1.
Complexity
- Time: O(n^3) to build the cost table (n^2 substrings, each scanned across its divisors) plus O(n^2 * k) for the DP.
- Space: O(n^2) for the cost table and O(n * k) for the DP table.
Implementation
class Solution {
public int minimumChanges(String s, int k) {
int n = s.length();
int INF = Integer.MAX_VALUE / 2;
// cost[i][j] = min letter changes to make s[i..j] a semi-palindrome (length >= 2).
int[][] cost = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int L = j - i + 1;
int best = INF;
for (int d = 1; d < L; d++) {
if (L % d != 0) continue;
int changes = 0;
int m = L / d;
for (int g = 0; g < d; g++) {
int lo = 0, hi = m - 1;
while (lo < hi) {
if (s.charAt(i + g + lo * d) != s.charAt(i + g + hi * d)) changes++;
lo++;
hi--;
}
}
best = Math.min(best, changes);
}
cost[i][j] = best;
}
}
// dp[i][j] = min changes to split the first i chars into j semi-palindrome parts.
int[][] dp = new int[n + 1][k + 1];
for (int[] row : dp) Arrays.fill(row, INF);
dp[0][0] = 0;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= Math.min(i / 2, k); j++) {
for (int p = 2 * (j - 1); p <= i - 2; p++) { // last part s[p..i-1], length i - p >= 2
if (dp[p][j - 1] != INF) {
dp[i][j] = Math.min(dp[i][j], dp[p][j - 1] + cost[p][i - 1]);
}
}
}
}
return dp[n][k];
}
}