fork download
  1. import java.util.*;
  2.  
  3. class Main {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6. int n = scanner.nextInt(); // size of the array
  7. int k = scanner.nextInt(); // maximum distinct elements allowed
  8. int[] b = new int[n];
  9. for (int i = 0; i < n; i++) {
  10. b[i] = scanner.nextInt(); // input array elements
  11. }
  12.  
  13. int count = 0; // to count valid subarrays
  14. Map<Integer, Integer> g = new HashMap<>(); // hashmap to store frequency of elements
  15.  
  16. for (int i = 0, j = 0; j < n; j++) {
  17. // Add new elements on the right
  18. g.put(b[j], g.getOrDefault(b[j], 0) + 1);
  19.  
  20. // While the size of the hashmap exceeds k, shrink from the left
  21. while (g.size() > k) {
  22. g.put(b[i], g.get(b[i]) - 1);
  23. if (g.get(b[i]) == 0) {
  24. g.remove(b[i]);
  25. }
  26. i++;
  27. }
  28.  
  29. // Count subarrays ending at j
  30. count += (j - i + 1); // All subarrays from i to j are valid
  31. }
  32.  
  33. System.out.println(count); // Output the count of valid subarrays
  34. }
  35. }
  36.  
Success #stdin #stdout 0.11s 56560KB
stdin
4 2
1 2 2 3
stdout
9