-
Notifications
You must be signed in to change notification settings - Fork 0
/
alg.subarray_with_max_sum.cpp
106 lines (95 loc) · 1.99 KB
/
alg.subarray_with_max_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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
using namespace std;
int findMaxSum(vector<int> a, int n)
{
int ans = a[0],
ans_l = 0,
ans_r = 0,
sum = 0,
min_sum = 0,
min_pos = -1;
for (int r = 0; r < n; ++r) {
sum += a[r];
int cur = sum - min_sum;
if (cur > ans) {
ans = cur;
ans_l = min_pos + 1;
ans_r = r;
}
if (sum < min_sum) {
min_sum = sum;
min_pos = r;
}
}
return ans;
}
int main()
{
int n;
cin >> n;
vector<int> a(n);
vector<tuple<int, int> > minPosSumVect;
for (int &i: a)
cin >> i;
int maxSum = findMaxSum(a, a.size());
int maxEl1 = -INF;
int minEl1 = INF;
int idx1, idx2;
int ans = a[0],
ans_l = 0,
ans_r = 0,
sum = 0,
min_sum = 0,
min_pos = -1;
minPosSumVect.push_back(tuple<int, int>(min_pos, min_sum));
vector<int> vectL;
vector<int> vectR;
for (int r = 0; r < n; ++r) {
sum += a[r];
int cur = sum - min_sum;
if (cur == maxSum) {
ans = cur;
ans_l = min_pos + 1;
ans_r = r;
for (int i = 0; i < minPosSumVect.size(); ++i)
{
if (get<1>(minPosSumVect[i]) == min_sum)
{
vectL.push_back(get<0>(minPosSumVect[i]));
vectR.push_back(ans_r);
}
}
}
if (sum <= min_sum) {
min_sum = sum;
min_pos = r;
minPosSumVect.push_back(tuple<int, int>(min_pos, min_sum));
}
}
if (equal(vectR.begin() + 1, vectR.end(), vectR.begin()))
{
for (int i = 0; i < vectL.size(); ++i)
{
if (maxEl1 <= vectL[i])
{
maxEl1 = vectL[i];
idx1 = i;
}
}
cout << vectL[idx1] + 2 << endl;
cout << vectR[0] + 1 << endl;
}
else
{
for (int i = 0; i < vectR.size(); ++i)
{
if (minEl1 >= vectR[i])
{
minEl1 = vectR[i];
idx2 = i;
}
}
cout << vectL[idx2] + 2 << endl;
cout << vectR[idx2] + 1 << endl;
}
}