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 z:");
  21. int z = scanner.nextInt();
  22.  
  23. // System.out.println("Enter the value of m:");
  24. int m = scanner.nextInt();
  25.  
  26. // System.out.println("Enter the value of n:");
  27. int n = scanner.nextInt();
  28.  
  29. // Calculate the number of valid subarrays
  30. int result = countValidSubarrays(nums, d, z, m, n);
  31. System.out.println("Number of valid subarrays: " + result);
  32. }
  33.  
  34. public static int countValidSubarrays(int[] nums, int d, int z, int m, int n) {
  35. int N = nums.length;
  36. int c1 = 0, c2=0 ;
  37. int subArray = 0;
  38. Map<Integer, Integer> map = new HashMap<>();
  39. map.put(0,1);
  40.  
  41. for (int i = 0; i < N; i++) {
  42. if(nums[i]==d) c1++;
  43. if(nums[i]==z) c2++;
  44. if(c1==0 && c2==0) continue;
  45. int key = (m * c2) - (n * c1);
  46. if(map.containsKey(key)){
  47. subArray+=map.get(key);
  48. }
  49. map.put(key, map.getOrDefault(key, 0) + 1);
  50. }
  51.  
  52. return subArray;
  53. }
  54. }
  55.  
Success #stdin #stdout 0.17s 59008KB
stdin
6
2 1 2 1 1 3
2 
1
1 
1
stdout
Number of valid subarrays: 5