fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. }
  14. }
  15.  
  16. class GfG {
  17. static int cntSubarrays(int[] arr, int k) {
  18.  
  19. // HashMap to store prefix sums frequencies
  20. Map<Integer, Integer> prefixmap = new HashMap<>();
  21. int res = 0;
  22. int currSum = 0;
  23.  
  24. for (int i = 0; i < arr.length; i++) {
  25. currSum += arr[i];
  26.  
  27. if (currSum == k)
  28. res++;
  29.  
  30. if (prefixmap.containsKey(currSum - k))
  31. res += prefixmap.get(currSum - k);
  32. prefixmap.put(currSum, prefixmap.getOrDefault(currSum, 0) + 1); //will make a pair with every such occurance
  33. }
  34.  
  35. return res;
  36. }
  37.  
  38. }
Success #stdin #stdout 0.11s 54616KB
stdin
Standard input is empty
stdout
Standard output is empty