-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubArray.cpp
61 lines (52 loc) · 941 Bytes
/
SubArray.cpp
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
#include<iostream>
#include<vector>
using namespace std;
struct window
{
int start,end;
int sum;
};
void solve(){
int N;
cin >> N;
int SUM ;
cin >> SUM;
vector<int> arr;
for(int i = 0; i< N; i++){
int tmp;
cin >> tmp;
arr.push_back(tmp);
}
//calculate the subarray using window approach
window win;
win.start = win.end = 0;
win.sum = arr[0];
for (int i = 1; i< N; i++){
if(win.sum == SUM){
break;
}
else{
win.sum+= arr[i];
win.end++;
while(win.sum > SUM){
win.sum-=arr[win.start];
win.start++;
}
}
}
if(win.sum == SUM) {
cout << win.start+1 << " "<< win.end+1<<endl;
}
else {
cout << -1;
}
}
int main()
{
int T;
cin >> T;
while(T--){
solve();
}
return 0;
}