-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstant_Subsequence.cpp
More file actions
63 lines (52 loc) · 1.47 KB
/
Constant_Subsequence.cpp
File metadata and controls
63 lines (52 loc) · 1.47 KB
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
#include <bits/stdc++.h>
using namespace std;
int maxSubarraySum(const vector<int>& arr) {
int maxSum = arr[0], currentSum = arr[0];
for (size_t i = 1; i < arr.size(); ++i) {
currentSum = max(arr[i], currentSum + arr[i]);
maxSum = max(maxSum, currentSum);
}
return maxSum;
}
int minimizeMaxSubarraySum(int n, const vector<int>& arr) {
vector<int> positives, negatives;
for (int num : arr) {
if (num >= 0) {
positives.push_back(num);
} else {
negatives.push_back(num);
}
}
vector<int> merged;
size_t posIdx = 0, negIdx = 0;
bool insertPositive = !positives.empty();
while (posIdx < positives.size() || negIdx < negatives.size()) {
if (insertPositive && posIdx < positives.size()) {
merged.push_back(positives[posIdx++]);
} else if (!insertPositive && negIdx < negatives.size()) {
merged.push_back(negatives[negIdx++]);
}
insertPositive = !insertPositive;
}
return maxSubarraySum(merged);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
int ans = minimizeMaxSubarraySum(N, A);
if(ans < 0)
cout << 0 << endl;
else
cout << ans << endl;
}
return 0;
}