# Maximum Sum Circular Subarray in C++

C++Server Side ProgrammingProgramming

Suppose we have a circular array C of integers represented by A, we have to find the maximum possible sum of a non-empty subarray of C. Also, a subarray may only include each element of the fixed buffer A at most once. If the array is like [1,-2,3,-2], then the output will be 3. This is because subarray has maximum sum 3.

To solve this, we will follow these steps −

• n := size of v

• create arrays leftSum, leftSumMax, rightSum, rightSumMax all of size n

• leftSum := v, leftSumMax := maximum of 0 and v

• for i in range 1 to n – 1

• leftSum[i] := leftSum[i - 1] + v[i]

• leftSumMax[i] := maximum of leftSum[i] and leftSumMax[i - 1]

• rightSum[n - 1] := v[n - 1], leftSumMax[n - 1] := maximum of 0 and v[n - 1]

• for i in range n - 2 down to 0

• rightSum[i] := rightSum [i + 1] + v[i]

• rightSumMax[i] := maximum of rightSum[i + 1] and rightSum Max[i]

• leftAns := leftSum + rightSumMax

• for i in range 1 to n – 2

• leftAns := maximum of leftAns, leftSum[i] + rightSumMax[i + 1]

• rightAns := rightSum[n - 1] + leftSumMax[n - 2]

• for i in range n - 2 down to 1

• rightAns := maximum of rightAns, rightSum[i] + leftSumMax[i - 1]

• curr := v, kadane := v

• for i in range 1 to n – 1

• curr := max of v, curr + v[i]

• return the max of leftAns, rightAns and kadane

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxSubarraySumCircular(vector<int>& v) {
int n = v.size();
vector <int> leftSum(n),leftSumMax(n),rightSum(n), rightSumMax(n);
leftSum = v;
leftSumMax = max((int)0,v);
for(int i =1;i<n;i++){
leftSum[i] = leftSum[i-1] + v[i];
leftSumMax[i] = max(leftSum[i],leftSumMax[i-1]);
}
rightSum[n-1] = v[n-1];
rightSumMax[n-1] = max((int)0,v[n-1]);
for(int i =n-2;i>=0;i--){
rightSum[i] = rightSum[i+1]+v[i];
rightSumMax[i] = max(rightSumMax[i+1],rightSum[i]);
}
int leftAns=leftSum+rightSumMax;
for(int i =1;i<n-1;i++){
leftAns = max(leftAns,leftSum[i]+rightSumMax[i+1]);
}
int rightAns = rightSum[n-1]+leftSumMax[n-2];
for(int i =n-2;i>=1;i--){
rightAns = max(rightAns,rightSum[i]+leftSumMax[i-1]);
}
int curr=v;
for(int i =1;i<n;i++){
curr = max(v[i],curr+v[i]);
}
}
};
main(){
vector<int> v = {1,-2,3,-2};
Solution ob;
cout << (ob.maxSubarraySumCircular(v));
}

## Input

[1,-2,3,-2]

## Output

3