forked from komalsingh1/Must-Do-Interview-Questions-DS-Algo-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarray with given sum.cpp
More file actions
34 lines (34 loc) · 832 Bytes
/
Copy pathSubarray with given sum.cpp
File metadata and controls
34 lines (34 loc) · 832 Bytes
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
//Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,i,sum,start=0;
cin>>n>>sum;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
int curr_sum=a[0];
for(i=1;i<=n;i++)
{
while(curr_sum>sum && start<i-1)
{
curr_sum-=a[start];
start++;
}
if(curr_sum==sum)
{
cout<<start+1<<" "<<i<<endl;
return 0;
}
if(i<n)
curr_sum+=a[i];
}
cout<<-1<<endl;
return 0;
}
}