-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubarray-with-given-sum
87 lines (70 loc) · 1.94 KB
/
Subarray-with-given-sum
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow.
Each test case consists of two lines.
The first line of each test case is N and S, where N is the size of array and S is the sum.
The second line of each test case contains N space separated integers denoting the array elements.
Output:
For each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray
from the left if sum equals to subarray, else print -1.
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= Ai <= 1010
Example:
Input:
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Output:
2 4
1 5
Explanation :
Testcase1: sum of elements from 2nd position to 4th position is 12
Testcase2: sum of elements from 1st position to 5th position is 15*/
#include<iostream>
using namespace std;
pair<int, int> solve(int *arr, int arraySize, int sum) {
int counter = 0, fsum = 0, end = 0;
for (int i = 0; i < arraySize; i++) {
if (fsum < sum) {
fsum += arr[i];
counter++;
end = i + 1;
}
else if (fsum == sum)
return pair<int, int>(i - counter + 1, i);
else {
i -= counter;
fsum = 0;
counter = 0;
}
}
if (fsum == sum)
return pair<int, int>(end - counter + 1, end);
else
return pair<int, int>(-1, -1);
}
void main() {
int testCases, arraySize, sum;
cout << "Number of test cases: ";
cin >> testCases;
for (int i = 0; i < testCases; i++) {
cout << "Array size: ";
cin >> arraySize;
cout << "Sum: ";
cin >> sum;
int *arr = new int[arraySize];
cout << "Elements of array: " << endl;
for (int j = 0; j < arraySize; j++) {
cin >> arr[j];
}
pair<int, int> par = solve(arr, arraySize, sum);
cout << "Solution: " << endl;
cout << par.first << " " << par.second << endl;
delete[] arr; arr = nullptr;
}
system("pause>0");
}