-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum_subsequence.cpp
102 lines (82 loc) · 1.66 KB
/
Maximum_subsequence.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
#include <bits/stdc++.h>
using namespace std;
void printarray(const vector<int> &a)
{
cout << "The array is: ";
for (int i = 0; i < a.size(); ++i)
{
cout << a[i] << " ";
}
cout << endl;
}
vector<int> maxCrossingSubarray(const vector<int> &input, int low, int high)
{
vector<int> output;
int mid = low + (high-low)/2;
int maxLeft = mid, maxRight = mid;
int leftSum = -99999, rightSum = -99999;
int sum = 0;
for (int i = mid; i >= low; i--)
{
sum = sum + input[i];
if (sum > leftSum)
{
leftSum = sum;
maxLeft = i;
}
}
sum = 0;
for (int i = mid; i <= high; i++)
{
sum = sum + input[i];
if (sum > rightSum)
{
rightSum = sum;
maxRight = i;
}
}
output.push_back(maxLeft);
output.push_back(maxRight);
output.push_back(leftSum + rightSum);
return output;
}
vector<int> maxSubarray(const vector<int> input, int low, int high)
{
vector<int> out;
if (high == low)
{
out.push_back(low);
out.push_back(high);
out.push_back(input[low]);
}
else
{
int mid = low + (high - low)/2;
vector<int> leftOut, rightOut, crossOut;
leftOut = maxSubarray(input, low, mid);
rightOut = maxSubarray(input, mid, high);
crossOut = maxCrossingSubarray(input, low, high);
if (leftOut[2] >= rightOut[2] && leftOut[2] >= crossOut[2])
return leftOut;
else if (rightOut[2] >= leftOut[2] && rightOut[2] >= crossOut[2])
return rightOut;
else
return crossOut;
}
}
int main()
{
vector<int> a, out;
int n;
cout << "Array size: ";
cin >> n;
cout << "Enter the array elements: ";
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
a.push_back(temp);
}
out = maxCrossingSubarray(a, 0, n-1);
printarray(out);
}