-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathMax_circular_subarray_sum.cpp
63 lines (53 loc) · 1.76 KB
/
Max_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
// C++ program for maximum contiguous circular sum problem
#include <bits/stdc++.h>
using namespace std;
// Standard Kadane's algorithm to
// find maximum subarray sum
int kadane(int a[], int n);
// The function returns maximum
// circular contiguous sum in a[]
int maxCircularSum(int a[], int n)
{
// Case 1: get the maximum sum using standard kadane'
// s algorithm
int max_kadane = kadane(a, n);
// if maximum sum using standard kadane' is less than 0
if(max_kadane < 0)
return max_kadane;
// Case 2: Now find the maximum sum that includes
// corner elements.
int max_wrap = 0, i;
for (i = 0; i < n; i++) {
max_wrap += a[i]; // Calculate array-sum
a[i] = -a[i]; // invert the array (change sign)
}
// max sum with corner elements will be:
// array-sum - (-max subarray sum of inverted array)
max_wrap = max_wrap + kadane(a, n);
// The maximum circular sum will be maximum of two sums
return (max_wrap > max_kadane) ? max_wrap : max_kadane;
}
// Standard Kadane's algorithm to find maximum subarray sum
// See https:// www.geeksforgeeks.org/archives/576 for details
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_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
/* Driver program to test maxCircularSum() */
int main()
{
int a[] = { 11, 10, -20, 5, -3, -5, 8, -13, 10 };
int n = sizeof(a) / sizeof(a[0]);
cout << "Maximum circular sum is " << maxCircularSum(a, n) << endl;
return 0;
}
// This is code is contributed by rathbhupendra