// C# program to implement
// the above approach
using System;
class GFG{
static int maxN = 20;
static int [,,,]dp =
new int[maxN, maxN,
27, maxN];
// Function which solves
// the desired problem
public static int solve(String s, int n,
int idx, int k,
char last, int count)
{
// idx: current index in s
// k: Remaining number of deletions
// last: Previous character
// count: Number of occurrences
// of the previous character
// Base Case
if (k < 0)
return n + 1;
// If the entire string
// has been traversed
if (idx == n)
return 0;
int ans = dp[idx, k, last -
'a', count];
// If precomputed subproblem
// occurred
if (ans != -1)
return ans;
ans = n + 1;
// Minimum run length encoding by
// removing the current character
ans = Math.Min(ans,
solve(s, n, idx + 1,
k - 1, last,
count));
// Minimum run length encoding by
// retaining the current character
int inc = 0;
if (count == 1 || count == 9 ||
count == 99)
inc = 1;
// If the current and the
// previous characters match
if (last == s[idx])
{
ans = Math.Min(ans, inc +
solve(s, n, idx + 1,
k, s[idx],
count + 1));
}
// Otherwise
else
{
ans = Math.Min(ans, 1 +
solve(s, n, idx + 1,
k, s[idx], 1));
}
return dp[idx, k, last -
'a', count] = ans;
}
// Function to return minimum
// run-length encoding for string
// s by removing atmost k characters
public static int MinRunLengthEncoding(String s,
int n, int k)
{
for (int i = 0; i < maxN; i++)
for (int j = 0; j < maxN; j++)
for (int p = 0; p < 27; p++)
for (int l = 0; l < maxN; l++)
dp[i, j, p, l] = -1;
return solve(s, n, 0,
k, (char)123, 0);
}
// Driver Code
public static void Main(String []args)
{
String S = "abbbcdcdd";
int N = 9, K = 2;
Console.WriteLine(
MinRunLengthEncoding(S,
N, K));
}
}
// This code is contributed by 29AjayKumar