-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_two_non_overlapping_sub_arrays_each_with_target_sum.cpp
79 lines (61 loc) · 1.41 KB
/
find_two_non_overlapping_sub_arrays_each_with_target_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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <bits/stdc++.h>
using namespace std;
// int findTwoNonoverlappingSubArraysEachWithTargetSum_topdown(vector<int> arr, int i, bool firstDone, int sum, int target) {
// if (target == sum) {
// if (firstDone) {
// return i + 1;
// } else {
// findTwoNonoverlappingSubArraysEachWithTargetSum_topdown(arr, i + 1, true, 0, target);
// }
// }
// }
int findTwoNonoverlappingSubArraysEachWithTargetSum_bottomup(vector<int> arr, int target) {
int sum = 0;
int firstSmallest = 10001, secondSmallest = 10001;
queue<int> aux;
int j;
for (int i = 0; i < arr.size(); i++) {
aux.push(arr[i]);
sum += arr[i];
while (sum > target) {
sum -= aux.front();
aux.pop();
}
if (sum == target) {
if (secondSmallest < firstSmallest) {
swap(firstSmallest, secondSmallest);
}
secondSmallest = min(secondSmallest, (int) aux.size());
sum = 0;
aux = {};
}
}
if (firstSmallest == 10001 || secondSmallest == 10001) {
return -1;
}
return firstSmallest + secondSmallest;
}
void solve() {
int target;
vector<int> arr;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> target;
arr.push_back(target);
}
cin >> target;
cout << findTwoNonoverlappingSubArraysEachWithTargetSum_bottomup(arr, target);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while(t--) {
solve();
}
return 0;
}