-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path05_SubarraysWithGivenSum.java
More file actions
34 lines (25 loc) · 987 Bytes
/
05_SubarraysWithGivenSum.java
File metadata and controls
34 lines (25 loc) · 987 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Problem: Subarrays with Given Sum
// Author: Atabul (codeByunique)
import java.util.HashMap;
class SubarraysWithGivenSum {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 1};
int targetSum = 5;
int count = countSubarraysWithSum(arr, targetSum);
System.out.println("Number of subarrays with sum " + targetSum + " = " + count);
}
public static int countSubarraysWithSum(int[] arr, int target) {
HashMap<Integer, Integer> prefixSumMap = new HashMap<>();
prefixSumMap.put(0, 1); // for subarrays starting from index 0
int count = 0;
int currentSum = 0;
for (int num : arr) {
currentSum += num;
if (prefixSumMap.containsKey(currentSum - target)) {
count += prefixSumMap.get(currentSum - target);
}
prefixSumMap.put(currentSum, prefixSumMap.getOrDefault(currentSum, 0) + 1);
}
return count;
}
}