fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static int countSubarraysOptimized(int[] arr, int k) {
  5. Map<Integer, Integer> prefixSumCount = new HashMap<>();
  6. int sum = 0, count = 0;
  7.  
  8. prefixSumCount.put(0, 1);
  9.  
  10. for (int num : arr) {
  11. sum += num;
  12.  
  13. if (prefixSumCount.containsKey(sum - k)) {
  14. count += prefixSumCount.get(sum - k);
  15. }
  16.  
  17. prefixSumCount.put(sum, prefixSumCount.getOrDefault(sum, 0) + 1);
  18. }
  19.  
  20. return count;
  21. }
  22.  
  23. public static void main(String[] args) {
  24. int[] arr = {1, 2, 3, 4, 5};
  25. int k = 5;
  26. System.out.println("Number of subarrays with sum " + k + ": " + countSubarraysOptimized(arr, k));
  27. }
  28. }
  29.  
Success #stdin #stdout 0.17s 57480KB
stdin
Standard input is empty
stdout
Number of subarrays with sum 5: 2