coderrohan14

Solution5Java

Sep 29th, 2021 (edited)
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Solution{
  4. public static void main(String[] args){
  5. Scanner sc = new Scanner(System.in);
  6. int t = sc.nextInt();
  7. StringBuilder ans = new StringBuilder("");
  8. while (t-- > 0) {
  9. int n = sc.nextInt(),k=sc.nextInt();
  10. char[] arr = sc.next().toCharArray();
  11. HashMap<Character,Integer> hm = new HashMap<>();
  12. int l=0,r=0,maxLen = Integer.MIN_VALUE;
  13. for(;r<n;r++){
  14. hm.put(arr[r], hm.getOrDefault(arr[r],0)+1);
  15. if(hm.size()<=k){
  16. maxLen = Math.max(maxLen,r-l+1);
  17. }else{
  18. while(hm.size()>k){
  19. hm.put(arr[l],hm.get(arr[l])-1);
  20. if(hm.get(arr[l])==0) hm.remove(arr[l]);
  21. l++;
  22. }
  23. maxLen = Math.max(maxLen,r-l+1);
  24. }
  25. }
  26. ans.append(maxLen+"\n");
  27. }
  28. System.out.println(ans);
  29. sc.close();
  30. }
  31. }
Add Comment
Please, Sign In to add comment