Skip to content

Commit e624641

Browse files
authored
Add files via upload
1 parent 2b64ad0 commit e624641

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Array/Subarray_with_given_sum.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
5+
// } Driver Code Ends
6+
7+
8+
// Function to find the subarray with given sum k
9+
// arr: input array
10+
// n: size of array
11+
vector<int> subarraySum(int arr[], int n, int s){
12+
int currSum = 0, i = 0, p = 0;
13+
for (i = 0; i < n; ++i){
14+
currSum += arr[i];
15+
while(currSum > s) currSum -= arr[p++];
16+
if(currSum == s){
17+
return {p+1, i+1};
18+
}
19+
}
20+
return {-1};
21+
22+
}
23+
24+
// { Driver Code Starts.
25+
26+
int main()
27+
{
28+
int t;
29+
cin>>t;
30+
while(t--)
31+
{
32+
int n;
33+
long long s;
34+
cin>>n>>s;
35+
int arr[n];
36+
37+
for(int i=0;i<n;i++)
38+
cin>>arr[i];
39+
40+
vector<int>res;
41+
res = subarraySum(arr, n, s);
42+
43+
for(int i = 0;i<res.size();i++)
44+
cout<<res[i]<<" ";
45+
cout<<endl;
46+
47+
}
48+
return 0;
49+
} // } Driver Code Ends

0 commit comments

Comments
 (0)