fork download
  1. import java.util.Scanner;
  2. import java.util.TreeMap;
  3.  
  4. public class Main {
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7. int n = sc.nextInt();
  8. int k = sc.nextInt();
  9. int[] nums = new int[n];
  10. for (int i = 0; i < n; i++) {
  11. nums[i] = sc.nextInt();
  12. }
  13. int count = countSubarrayWithMaxMinUptoK(nums, n, k);
  14. System.out.println(count);
  15. sc.close();
  16. }
  17.  
  18. public static int countSubarrayWithMaxMinUptoK(int[] nums, int n, int limit) {
  19. TreeMap<Integer, Integer> map = new TreeMap<>();
  20. int count = 0;
  21. for (int i = 0, j = 0; j < n; j++) {
  22. map.put(nums[j], map.getOrDefault(nums[j], 0) + 1);
  23. int max = map.lastKey();
  24. int min = map.firstKey();
  25. int absDiff = Math.abs(max - min);
  26. while (absDiff > limit) {
  27. if (map.get(nums[i]) == 1) {
  28. map.remove(nums[i]);
  29. } else {
  30. map.put(nums[i], map.get(nums[i]) - 1);
  31. }
  32. i++;
  33. max = map.lastKey();
  34. min = map.firstKey();
  35. absDiff = Math.abs(max - min);
  36. }
  37. count+=(j-i+1);
  38. }
  39. return count;
  40. }
  41. }
Success #stdin #stdout 0.17s 56640KB
stdin
7 3
2 6 4 3 6 8 9
stdout
16