-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathSubarray with given sum .java
More file actions
65 lines (51 loc) · 1.49 KB
/
Copy pathSubarray with given sum .java
File metadata and controls
65 lines (51 loc) · 1.49 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
import java.util.*;
import java.lang.*;
import java.io.*;
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
int s = sc.nextInt();
int[] m = new int[n];
for (int j = 0; j < n; j++) {
m[j] = sc.nextInt();
}
Solution obj = new Solution();
ArrayList<Integer> res = obj.subarraySum(m, n, s);
for(int ii = 0;ii<res.size();ii++)
System.out.print(res.get(ii) + " ");
System.out.println();
}
}
}// } Driver Code Ends
class Solution
{
//Function to find a continuous sub-array which adds up to a given number.
static ArrayList<Integer> subarraySum(int[] arr, int n, int s)
{
// Your code here
int start = 0;
int currSum = arr[0];
ArrayList<Integer> ret = new ArrayList<>();
for(int i=1;i<=n;i++)
{
while(currSum > s && start < i-1)
{
currSum -= arr[start];
start++;
}
if(currSum == s)
{
ret.add(start+1);
ret.add(i);
return ret;
}
if(i<n)
currSum += arr[i];
}
ret.add(-1);
return ret;
}
}