-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsubarray-with-given-sum.cpp
65 lines (58 loc) · 1.32 KB
/
subarray-with-given-sum.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
62
63
64
65
// https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0
#include <iostream>
using namespace std;
long long int li[10000001];
int main()
{
freopen("input.txt", "r", stdin);
//code
int testCase;
cin >> testCase;
long long int n;
long long int sum_target = 0;
long long int sum = 0;
bool found = false;
while (testCase--)
{
cin >> n;
cin >> sum_target;
found = false;
long long int left = 0;
long long int right = 0;
for (int i = 0; i < n; i++)
{
cin >> li[i];
}
if (n == 1 && li[0] != sum)
{
cout << -1 << endl;
continue;
}
sum = li[0];
while (right < n)
{
if (sum == sum_target)
{
cout << left + 1 << " " << right + 1 << endl;
found = true;
break;
}
else if (sum < sum_target)
{
right++;
if (right < n)
{
sum += li[right];
}
}
else if (sum > sum_target)
{
sum -= li[left];
left++;
}
}
if (!found)
cout << -1 << endl;
}
return 0;
}