-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Subarrays_With_Sum.java
More file actions
77 lines (68 loc) · 1.98 KB
/
Binary_Subarrays_With_Sum.java
File metadata and controls
77 lines (68 loc) · 1.98 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
import java.util.*;
import java.io.*;
import java.lang.*;
public class Binary_Subarrays_With_Sum {
class Solution {
public int numSubarraysWithSum(int[] nums, int goal) {
int n = nums.length;
int count = 0;
int left1 = 0, left2 = 0;
int sum1 = 0, sum2 = 0;
for (int right = 0; right < n; right++) {
sum1 += nums[right];
while (left1 <= right && sum1 > goal) {
sum1 -= nums[left1++];
}
sum2 += nums[right];
while (left2 <= right && sum2 >= goal) {
sum2 -= nums[left2++];
}
count += left2 - left1;
}
return count;
}
}
// class Solution {
// public int numSubarraysWithSum(int[] nums, int goal) {
// int count=0;
// for(int i=0;i<nums.length;i++){
// int currSum=0;
// for(int j=i;j<nums.length;j++){
// currSum+=nums[j];
// if(currSum==goal){
// count++;
// }
// else if(currSum > goal) break;
// }
// }
// return count;
// }
// }
// class Solution {
// public int numSubarraysWithSum(int[] nums, int goal) {
// int ans = 0;
// int n = nums.length;
// for(int i = 0 ; i<n ; i++)
// {
// ans += fun(i , 0 , nums , goal);
// }
// return ans;
// }
// public static int fun(int index , int sum , int[] nums , int goal)
// {
// if(index>=nums.length)
// {
// return 0;
// }
// if(sum + nums[index] == goal)
// {
// return 1 + fun(index+1 , sum+nums[index] , nums , goal);
// }
// else if(sum + nums[index] < goal)
// {
// return fun(index+1 , sum+nums[index] , nums , goal);
// }
// return 0;
// }
// }
}