-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMax_Sum_array_Divide.cpp
116 lines (105 loc) · 2.62 KB
/
Max_Sum_array_Divide.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
107
108
109
110
111
112
113
114
115
116
#include <iostream>
#include <vector>
using namespace std;
int n;
int *arr = NULL;
//Taking Input
void input()
{
cin>>n;
arr = new int[n];
for(int i=1; i<=n; i++)
cin>>arr[i];
}
vector<int> maxsum_mid_subarray(int left,int mid, int right)
{
//Left Part
int sum=0;
int left_sum=0;
int st=mid,Left_end=mid,Right_end=mid;
vector<int> sumCrossingMid;
for(int i=mid;i>=left;i--)
{
sum=sum+arr[i];
if(sum>=left_sum){
left_sum=sum;
Left_end=i;
}
}
//Right Part
sum=0;
int right_sum=0;
for(int i=mid+1;i<=right;i++)
{
sum=sum+arr[i];
if(sum>=right_sum){
right_sum=sum;
Right_end=i;
}
}
if(left_sum>= right_sum && left_sum >= left_sum+right_sum)
{
sumCrossingMid.push_back(Left_end);
sumCrossingMid.push_back(mid);
sumCrossingMid.push_back(left_sum);
}
if(right_sum>= left_sum && right_sum >= left_sum+right_sum)
{
sumCrossingMid.push_back(mid+1);
sumCrossingMid.push_back(Right_end);
sumCrossingMid.push_back(right_sum);
}
else
{
sumCrossingMid.push_back(Left_end);
sumCrossingMid.push_back(Right_end);
sumCrossingMid.push_back(left_sum+right_sum);
}
return sumCrossingMid;
}
int leftStart,leftEnd,leftMax,rightStart,rightEnd,rightMax,midStart,midEnd,midMax;
vector<int> maxsum_subarray(int left,int right)
{
vector<int> final;
if(left==right){
vector<int> base;
base.push_back(left);
base.push_back(right);
base.push_back(arr[left]);
return base;
}
int mid=(left+right)/2;
vector<int> leftMax = maxsum_subarray(left,mid);
vector<int> rightMax = maxsum_subarray(mid+1,right);
vector<int> midMax = maxsum_mid_subarray(left,mid,right);
if(leftMax[2] >= rightMax[2] and leftMax[2] >= midMax[2])
{
final.push_back(leftMax[0]);
final.push_back(leftMax[1]);
final.push_back(leftMax[2]);
}
else if(rightMax[2] >= leftMax[2] and rightMax[2] >= midMax[2])
{
final.push_back(rightMax[0]);
final.push_back(rightMax[1]);
final.push_back(rightMax[2]);
}
else
{
final.push_back(midMax[0]);
final.push_back(midMax[1]);
final.push_back(midMax[2]);
}
return final;
}
int main() {
input();
vector<int> Max_Sum= maxsum_subarray(1,n);
if(Max_Sum[2]!=0){
cout<<"Max sum is:"<<Max_Sum[2]<<endl;
cout<<"Index (i,j) is = ("<<Max_Sum[0]<<","<<Max_Sum[1]<<")";
}
else
cout<< "-1";
return 0;
}