Problem Statement
Pattern: Pattern Prefix Array
Solution
public static int subArraySum(int[] nums, int k) {
Integer count = 0, currSum = 0;
Map<Integer, Integer> map = new HashMap<>();
// edge case
map.put(currSum, 1);
for (int index = 0; index < nums.length; index++) {
// update currSum at index
currSum += nums[index];
// get freq of currSum-k
Integer freq = map.get(currSum - k);
// if freq found update count
if (freq != null) count += freq;
// increment currSum freq
map.put(currSum, map.getOrDefault(currSum, 0) + 1);
}
return count;
}Notes
-
In kadanes algo we know that
- for a max sum problem
- a negative
currSumwould never contribute to the a globalmaxvalue
- a negative
- for a min sum problem
- a positive
currSumwould never contribte to a globalminvalue
- a positive
- so we reset
currSumto the next element, and keep updatingmaxandmin
- for a max sum problem
-
Concept : update freq of
currSumfor each element in a hashmap- At any given index if
map.get(currSum-k)let’s say is2that means, 2 subarrays with the sumkexist!!! only then would asum = currSum-kwould exist! - update the
countwith2 - so on…
- At any given index if
-
edge case, if
currSum == kthenmap.get(0)should return 1.