fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int n = sc.nextInt();
  7. int k = sc.nextInt();
  8.  
  9. int[] nums = new int[n];
  10. for (int i = 0; i < n; i++) {
  11. nums[i] = sc.nextInt();
  12. }
  13. int cnt = 0;
  14. int sum = 0;
  15.  
  16. Map<Integer, Integer> map = new HashMap<>();
  17. int i=0;
  18. for (int j = 0; j < n; j++) {
  19. map.put(nums[j], map.getOrDefault(nums[j], 0) + 1);
  20. int d = map.size();
  21. while (d > k) {
  22. map.put(nums[i], map.get(nums[i]) - 1);
  23. if (map.get(nums[i]) == 0) {
  24. map.remove(nums[i]);
  25. }
  26. i++;
  27. d = map.size();
  28. }
  29. cnt += (j - i + 1);
  30. }
  31. System.out.println(cnt);
  32. sc.close();
  33. }
  34. }
  35.  
Success #stdin #stdout 0.18s 56640KB
stdin
3 2 
1 2 3 
stdout
5