-
Notifications
You must be signed in to change notification settings - Fork 3
/
Maximum_circular_subarray_sum.cpp
63 lines (62 loc) · 1.42 KB
/
Maximum_circular_subarray_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
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int kadane(int a[], int n)
{
int max_so_far = 0, max_ending_here = 0;
int i;
for (i = 0; i < n; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
int main() {
//code
int i,t,n,*a,back_sum,back_max,still_max,sum,max,f;
cin>>t; //enter number of test cases
while(t--)
{
f=0;
max=INT_MIN;
back_sum=0;
back_max=INT_MIN;
still_max=INT_MIN;
sum=0;
cin>>n; // enter size of array
a=new int[n];
for(i=0;i<n;i++)
{
cin>>a[i]; // enter values of array
sum+=a[i];
max=max>a[i]?max:a[i];
if(a[i]>=0&&f==0)
{
f=1;
}
}
if(f==0) // if all elments are negative
{
cout<<max<<endl;
continue;
}
still_max=kadane(a,n);
for(i=0;i<n;i++)
{
back_sum+=a[i];
back_max=back_max>back_sum?back_max:back_sum;
sum=sum-a[i];
if(sum+back_max>still_max)
{
still_max=sum+back_max;
}
}
cout<<still_max<<endl;
delete[] a;
}
return 0;
}