find maximum sum of circular subarray

Solutions on MaxInterview for find maximum sum of circular subarray by the best coders in the world

showing results for - "find maximum sum of circular subarray"
Louis
15 Jan 2019
1#include <iostream>
2
3using namespace std;
4
5int kadane(int arr[], int n)
6{
7    int currentSum = 0;
8    int maxSum = INT_MIN;
9    for (int i = 0; i < n; i++)
10    {
11        currentSum += arr[i];
12        if (currentSum < 0)
13        {
14            currentSum = 0;
15        }
16        maxSum = max(maxSum, currentSum);
17    }
18
19    return maxSum;
20}
21int main()
22{
23    //Input Array
24    int n;
25    cin >> n;
26    int arr[n];
27    for (int i = 0; i < n; i++)
28    {
29        cin >> arr[i];
30    }
31
32    int wrapsum, totalsum = 0;
33    int nonwrapsum;
34
35    nonwrapsum = kadane(arr, n);
36
37    for (int i = 0; i < n; i++)
38    {
39        totalsum += arr[i];
40        arr[i] = -arr[i];
41    }
42    wrapsum = totalsum + kadane(arr, n);
43    cout << max(wrapsum, nonwrapsum) << endl;
44
45    return 0;
46}