-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrefixSum.java
More file actions
85 lines (58 loc) · 2.12 KB
/
Copy pathPrefixSum.java
File metadata and controls
85 lines (58 loc) · 2.12 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.*;
class PrefixSum{
public static int pivotIndexUnderstanding(int[] nums) {
int n = nums.length;
int[] prefix = new int[n];
int[] suffix = new int[n];
prefix[0] = 0;
for(int i = 1;i < n;i++){
prefix[i] = prefix[i-1] + nums[i-1];
}
suffix[n-1] =0;
for(int i = n-2;i >=0;i--){
suffix[i] = suffix[i+1] + nums[i+1];
}
for(int i = 0;i < n;i++){
if(prefix[i] == suffix[i]){
return i;
}
}
return -1;
}
public static int pivotIndexOptimal(int[] nums) {
int totalSum = Arrays.stream(nums).sum();
int leftSum = 0;
for (int i = 0; i < nums.length; i++) {
int rightSum = totalSum - leftSum - nums[i];
if (leftSum == rightSum) {
return i;
}
leftSum += nums[i];
}
return -1;
}
public static int subarraySum(int[] nums, int k) {
int sum = 0;
int res = 0;
HashMap<Integer,Integer> map = new HashMap<>();
map.put(0,1); // for possibility that complete array sum is k and sum - k = 0
for(int i = 0;i < nums.length;i++){
sum += nums[i];
int question = sum - k; // named variable as question, becoz this we will be asking to themap have u seen this before
int freq = map.getOrDefault(question, 0);
if(freq > 0){
res += freq; // we are not doing res++ and instead doing += freq becoz there can be multiple instance of that sum, whhich tell more than one subarray ended over there, so we should consider them all
}
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return res;
}
public static void main(String[] args) {
int[] nums = {1, 7, 3, 6, 5, 6};
// System.out.println(pivotIndexUnderstanding(nums));
//System.out.println(pivotIndexOptimal(nums));
int[] nums2 = {3, 4, 7, 2, -3, 1, 4, 3};
int k = 7;
System.out.println(subarraySum(nums2, k));
}
}