forked from PRAteek-singHWY/hackoctoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarray_with_given_Sum.cpp
More file actions
53 lines (42 loc) · 845 Bytes
/
Subarray_with_given_Sum.cpp
File metadata and controls
53 lines (42 loc) · 845 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
50
51
52
53
#include <iostream>
#include <vector>
using namespace std;
vector<int> subarraySum(vector<int> &arr, int sum)
{
int start = 0, curr_sum = 0;
int n = arr.size();
for (int end = 0; end < n; end++)
{
curr_sum += arr[end];
while (curr_sum > sum && start < end)
{
curr_sum -= arr[start];
start++;
}
if (curr_sum == sum)
{
return {start + 1, end + 1};
}
}
return {-1};
}
int main()
{
int N;
cin >> N;
vector<int> A;
for (int i = 0; i < N; i++)
{
int a;
cin >> a;
A.push_back(a);
}
int target_sum;
cin >> target_sum;
vector<int> ans = subarraySum(A, target_sum);
if (ans[0] != -1)
{
cout << ans[0] << " to " << ans[1] << endl;
}
return 0;
}