-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarray_with_given_sum.cpp
More file actions
49 lines (38 loc) · 897 Bytes
/
Subarray_with_given_sum.cpp
File metadata and controls
49 lines (38 loc) · 897 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// Function to find the subarray with given sum k
// arr: input array
// n: size of array
vector<int> subarraySum(int arr[], int n, int s){
int currSum = 0, i = 0, p = 0;
for (i = 0; i < n; ++i){
currSum += arr[i];
while(currSum > s) currSum -= arr[p++];
if(currSum == s){
return {p+1, i+1};
}
}
return {-1};
}
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
long long s;
cin>>n>>s;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
vector<int>res;
res = subarraySum(arr, n, s);
for(int i = 0;i<res.size();i++)
cout<<res[i]<<" ";
cout<<endl;
}
return 0;
} // } Driver Code Ends