-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubsum3.cpp
More file actions
47 lines (36 loc) · 1.1 KB
/
subsum3.cpp
File metadata and controls
47 lines (36 loc) · 1.1 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
#include <iostream>
#include <vector>
using namespace std;
#include "sequence.h"
int maxSubSum3 (const vector<int>& a);
int maxSumRec (const vector<int>&a, int left, int right);
int main () {
for (auto i: sequence)
cout << i << " ";
cout << ": " << maxSubSum3(sequence) << endl;
return 0;
}
int maxSubSum3 (const vector<int>& a) {
return maxSumRec(a, 0, a.size() - 1);
}
int maxSumRec (const vector<int>&a, int left, int right) {
if (left == right)
return a[left] > 0 ? a[left] : 0;
int center = (left + right) / 2;
int maxLeftSum = maxSumRec(a, left, center);
int maxRightSum = maxSumRec(a, center + 1, right);
int maxLeftBorderSum = 0, leftBorderSum = 0;
for (int i = center; i >= left; i--) {
leftBorderSum += a[i];
if (leftBorderSum > maxLeftBorderSum)
maxLeftBorderSum = leftBorderSum;
}
int maxRightBorderSum = 0, rightBorderSum = 0;
for (int i = center + 1; i <= right; i++) {
rightBorderSum += a[i];
if (rightBorderSum > maxRightBorderSum)
maxRightBorderSum = rightBorderSum;
}
return max(max(maxLeftSum, maxRightSum),
maxLeftBorderSum + maxRightBorderSum);
}