fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner s=new Scanner(System.in);
  13. int N=s.nextInt();
  14. int a[]=new int[N];
  15. for(int i=0;i<N;i++){
  16. a[i]=s.nextInt();
  17. }
  18. int k=s.nextInt();
  19. HashMap<Integer,Integer> arr=new HashMap<>();
  20. int si=0,ei=0,maxlen=0;
  21. while(ei<N){
  22. arr.put(a[ei],arr.getOrDefault(a[ei],0)+1);
  23. while(arr.size()>k){
  24.  
  25. arr.put(a[si],arr.getOrDefault(a[si],0)-1);
  26. if(arr.get(a[si])==0)
  27. {
  28. arr.remove(a[si]);
  29. }
  30. si++;
  31. }
  32.  
  33.  
  34. maxlen=Math.max(maxlen,(ei-si)+1);
  35. ei++;
  36.  
  37. }
  38. System.out.println(maxlen);
  39.  
  40.  
  41. }
  42. }
Success #stdin #stdout 0.14s 56644KB
stdin
11
3 3 3 1 2 1 1 2 3 3 4
2
stdout
5