

Change some characters of ‘S’ to other lowercase letters (if required).
Divide ‘S’ into ‘K’ non-empty disjoint substrings such that each substring is a palindrome.
The first line of input contains an integer 'T' representing the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘K’. Here ‘N’ denotes the length of the string, and ‘K’ is an integer given by Alice.
The next line contains a string ‘S’ of length ‘N’. Here ‘S’ is the string given by Alice to Bob.
For each test case, print a single line containing a single integer denoting the minimum number of characters that Bob needs to change to divide ‘S’ into ‘K’ non-empty disjoint palindromic substrings.
The output of each test case will be printed in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N <= 50
1 <= K <= N
‘S’ contains only lowercase English letters.
Time limit: 1 sec.
The idea here is to check all possible partitions such that it divides the given string into exactly ‘K’ non-empty disjoint substrings. We will try to divide the given string into ‘K’ non-empty disjoint substrings. We will calculate the minimum number of changes required to make it a palindrome for each substring and then we will take the sum of all ‘K’ substrings to get the minimum number of required changes for the whole string. Recursively we will try all possible divisions and compute their corresponding minimum number of changes. Finally, we will take a minimum of all such divisions.
Algorithm:
Description of ‘numChanges’ function
This function will take three parameters:
int numChanges(str, low, high):
Description of ‘allPartitions’ function
This function will take three parameters :
int allPartitions(low, high,k):
The idea here is to optimize the previous approach using dynamic programming. We are calling some functions again and again so we will call them once and store their values in a ‘dp’ array.
The below diagram shows that allPartitions(3, 4, 1) is called multiple times, hence there are overlapping subproblems
Algorithm:
Description of ‘numChanges’ function
This function will take three parameters :
int numChanges(str, low, high):
Description of ‘allPartitions’ function
This function will take three parameters :
int allPartitions(low, high, k):
The idea here is to use iterative dynamic programming. We will calculate answers from bottom to top. We will create 2 2 - D arrays ‘changes[N][N]’ and ‘dp[N][K]’. ‘Changes[i][j]’ will store the minimum number of characters that we need to change to make substring ‘S[ i. . .j]’ a palindrome and ‘dp[i][k]’ will store the minimum number of characters that we need to change to divide the substring ‘S[i. . .N]’ into ‘K’ non-empty disjoint palindromic substrings.
Algorithm: