Subarray with Given Sum 8

Sort by

recency

|

1 Discussion

|

  • + 0 comments

    prefix sum based solution

        public static long countNumberOfSubarrays(List<Integer> arr, int k) {
            long result = 0;
            long sum = 0;
    
            Map<Long, Integer> map = new HashMap<>();
            map.put(0L, 1);
    
            for (long integer : arr) {
                sum += integer;
                if (map.containsKey(sum - k)) {
                    result += map.get(sum - k);
                }
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
            System.out.println(result);
    
            return result;
        }
    

No more comments