fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int[] arr = new int[]{9, 4, 20, 3, 10, 5};
  6. int k = 33;
  7.  
  8. System.out.println(countSubarraysWithSum(arr, k));
  9. }
  10.  
  11. public static int countSubarraysWithSum(int[] arr, int k) {
  12.  
  13. Map<Integer, Integer> map = new HashMap<>();
  14.  
  15.  
  16. map.put(0, 1);
  17.  
  18. int currentSum = 0;
  19. int count = 0;
  20.  
  21. for (int num : arr) {
  22.  
  23. currentSum += num;
  24.  
  25.  
  26. if (map.containsKey(currentSum - k)) {
  27. count += map.get(currentSum - k);
  28. }
  29.  
  30.  
  31. map.put(currentSum, map.getOrDefault(currentSum, 0) + 1);
  32. }
  33.  
  34. return count;
  35. }
  36. }
  37.  
Success #stdin #stdout 0.07s 54548KB
stdin
Standard input is empty
stdout
2