// Java code for the above approach
import java.io.*;
import java.util.*;
class GFG {
static int maxLen = 0;
// Function to check whether all the characters in the
// substring are continuous or not
static boolean iscontinuous(String temp)
{
Map<Character, Integer> last_Pos = new HashMap<>();
for (int i = 0; i < temp.length(); i++) {
if (last_Pos.containsKey(temp.charAt(i))) {
if (i - last_Pos.get(temp.charAt(i)) + 1
<= 1) {
last_Pos.put(
temp.charAt(i),
last_Pos.get(temp.charAt(i)) + 1);
}
else {
return false;
}
}
else {
last_Pos.put(
temp.charAt(i),
last_Pos.getOrDefault(temp.charAt(i), 0)
+ 1);
}
}
return true;
}
// Function to find the all the substrings
static void generateSubSequences(String str,
String temp, int j,
int k)
{
HashMap<Character, Integer> freq = new HashMap<>();
if (j == str.length()) {
if (temp.length() > 0) {
int minfreq = Integer.MAX_VALUE,
maxfreq = Integer.MIN_VALUE;
freq.clear();
for (int i = 0; i < temp.length(); i++) {
freq.put(
temp.charAt(i),
freq.getOrDefault(temp.charAt(i), 0)
+ 1);
}
for (int i : freq.values()) {
minfreq = Math.min(minfreq, i);
maxfreq = Math.max(maxfreq, i);
}
if (maxfreq - minfreq <= k
&& iscontinuous(temp)) {
maxLen = Math.max(maxLen,
(int)temp.length());
}
}
return;
}
generateSubSequences(str, temp, j + 1, k);
temp += str.charAt(j);
generateSubSequences(str, temp, j + 1, k);
}
public static void main(String[] args)
{
String str = "abba", temp = "";
int k = 1;
generateSubSequences(str, temp, 0, k);
System.out.print(maxLen);
}
}
// This code is contributed by lokeshmvs21.