-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarraywithGivenSum.java
More file actions
58 lines (54 loc) · 1.56 KB
/
SubarraywithGivenSum.java
File metadata and controls
58 lines (54 loc) · 1.56 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
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Scanner;
class GFG {
public static void main (String[] args) {
Scanner inp = new Scanner(System.in);
String numOfTests = inp.nextLine();
int T = Integer.parseInt(numOfTests);
for (int i=0; i<T;i++){
String[] firstLine = inp.nextLine().split(" ");
String[] secondLine = inp.nextLine().split(" ");
int N = Integer.parseInt(firstLine[0]);
int S = Integer.parseInt(firstLine[1]);
int[] A = new int[N];
for (int j=0; j<N; j++){
A[j] = Integer.parseInt(secondLine[j]);
}
int[] locations = arrayLocations(N, S, A);
if (locations[0] == -1){
System.out.println(-1);
}
else{
System.out.println(locations[0]+" "+locations[1]);
}
}
}
public static int[] arrayLocations(int N, int S, int A[]){
int[] locations = new int [2];
boolean found = false;
for (int i = 0; i < N; i++){
int sum = 0;
for (int j = i; j < N; j++){
sum+=A[j];
if (sum>S){
break;
}
if (sum==S){
locations[1] = j+1;
found = true;
break;
}
}
if (found){
locations[0] = i+1;
break;
}
}
if (!found){
locations[0] = -1;
}
return locations;
}
}