Just change chars > 2 to chars > k.

```
int max = 0;
int chars = 0; //How many different chars so far.
for (int i = 0, j = 0; i < s.length(); i++) {
if (map[s.charAt(i)]++ == 0) {
chars++;
}
while (chars > 2) {
if (map[s.charAt(j++)]-- == 1) {
chars--;
}
}
max = Math.max(max, i - j + 1);
}
return max;
```