2
public int getLengthOfOptimalCompression(String s, int k) {3
Map<String, Integer> memo = new HashMap<>();4
return recur(s, '\u0000', 0, k, 0, memo);8
String s, char prevChar, int prevCharCount, int k, int index, Map<String, Integer> memo) {10
if (index == s.length()) {13
String key = prevChar + ", " + prevCharCount + ", " + k + ", " + index;14
Integer keyVal = memo.get(key);19
char ch = s.charAt(index);21
int nextIndex = index + 1;23
for (int i = index + 1; i < s.length(); i++) {25
if (s.charAt(i) == ch) {33
int totalCount = count;34
int prevCountRepresentation = 0;35
// if prev char is equal to current char that means we have removed middle element36
// So we have to subtract the previous representation length and add the new encoding37
// representation length39
totalCount += prevCharCount;40
prevCountRepresentation = getLength(prevCharCount);43
int representaionLength = getLength(totalCount);46
+ recur(s, ch, totalCount, k, nextIndex, memo)47
- prevCountRepresentation;51
for (int i = 1; i <= k && i <= count; i++) {52
int currentCount = totalCount - i;53
int length = getLength(currentCount);54
// checking if we have to send current char and current char count or previous char55
// and previous char count60
currentCount == 0 ? prevChar : ch,61
currentCount == 0 ? prevCharCount : currentCount,65
- prevCountRepresentation;66
ans = Math.min(ans, holder);73
// Since length for aaaaa will be a5(2) aaaaaaaaaa a10(3) etc.74
private int getLength(int n) {