-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubArraySumEqualsK.java
39 lines (35 loc) · 1.01 KB
/
SubArraySumEqualsK.java
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
class SubArraySumEqualsK {
public static void main(String[] args) {
int[] arr = {1, -1, 0};
System.out.println(subarraySum(arr, 0));
}
public static int subarraySum(int[] nums, int k) {
int count = 0;
int left = 0, right = 0, sum = nums[0];
while (right < nums.length) {
while (left < right && sum > k) {
sum = sum - nums[left];
left++;
}
while (left < right && right == nums.length - 1 && sum < k) {
sum = sum - nums[left];
left++;
}
while (left < right && right == nums.length - 1) {
sum = sum - nums[left];
left++;
if (sum == k) {
count++;
}
}
if (sum == k) {
count++;
}
right++;
if (right < nums.length) {
sum += nums[right];
}
}
return count;
}
}