fork download
  1. import java.util.*;
  2. //https://docs.google.com/document/d/1A-D63VjskOCGUV_mZmQg1lLX2zDf7Z04y5Nu7SJM5WA/edit?tab=t.0
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6.  
  7. // Read input values
  8. System.out.println("Enter the size of the array (N):");
  9. int N = scanner.nextInt();
  10.  
  11. int[] nums = new int[N];
  12. System.out.println("Enter the elements of the array:");
  13. for (int i = 0; i < N; i++) {
  14. nums[i] = scanner.nextInt();
  15. }
  16.  
  17. System.out.println("Enter the value of D:");
  18. int D = scanner.nextInt();
  19.  
  20. System.out.println("Enter the value of M:");
  21. int M = scanner.nextInt();
  22.  
  23. // Calculate the number of subarrays
  24. int result = countSubarraysWithD(nums, D, M);
  25. System.out.println("Number of subarrays: " + result);
  26. }
  27.  
  28. public static int countSubarraysWithD(int[] nums, int d, int m) {
  29. int n = nums.length;
  30. Map<Integer, Integer> map = new HashMap<>();
  31. map.put(0,1);
  32. int count = 0;
  33. int subArray = 0;
  34. for(int i=0;i<n;i++){
  35. if(nums[i]==d) count++;
  36. int z = count - m;
  37. if(map.containsKey(z)){
  38. subArray+=map.get(z);
  39. }
  40. map.put(count, map.getOrDefault(count, 0)+1);
  41. }
  42. return subArray;
  43. }
  44. }
  45.  
Success #stdin #stdout 0.18s 57052KB
stdin
8
5 2 5 2 5 2 1 1
5
2
stdout
Enter the size of the array (N):
Enter the elements of the array:
Enter the value of D:
Enter the value of M:
Number of subarrays: 10