Advertisement
unknown_0711

Untitled

Jan 16th, 2023
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7. int n = sc.nextInt();
  8. int[] arr = new int[n];
  9. for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
  10. int k = sc.nextInt();
  11. System.out.println(subarraySum(arr, k));
  12. }
  13.  
  14. public static int subarraySum(int[] nums, int k) {
  15. Map<Integer, Integer> map = new HashMap<>();
  16. int n = nums.length, sum = 0, res = 0;
  17. map.put(sum, 1);
  18. for (int i = 0; i < n; i++) {
  19. sum += nums[i];
  20. if (map.containsKey(sum - k)) {
  21. res += map.get(sum - k);
  22. }
  23. if (map.containsKey(sum)) map.put(sum, map.get(sum) + 1);
  24. else map.put(sum, 1);
  25. }
  26. return res;
  27. }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement