I dont understand max circular subarray sum

i dont undertsand max circular sub array sum . please help me.

Here, you have to considered the given array as a circular sequence.
example:
for the array : {-1,2,8,-5,6}
the sub-sequences are:
{-1}=-1
{-1,2} = 1(sum)
{-1,2,8} = 9
{-1,2,8,-5}= 4
{-1,2,8,-5,6} = 10
{2]=2
{2,8} = 10
{2,8,-5}=5


{6}=6
{6,-1}=5 (coz array is considered circular)
{6,-1,2} =7

Now, you have to print the sum, that is maximum amongst all the sum computed.

can you also explain the code?

why are we inverting the array?

We have to consider two cases while solving this problem:

Case 1: When the maximum sum SubArray is present in the normal order of array.
Example,
{-10, 2, -1, 5}
Max sum is 5

{-2, 4, -1, 4, -1}
Max sum is 7 (4+(-1)+4)
Use Kadane’s algorithm

Case 2:When max sum subArray is Present in circular fashion.
Inversion of the array is required only to find the maximum sum in circular fashion.
Example,
{10, -12, 11}
The max sum is 21 (11+10)
Inverted array, {-10,12,-11}
Maximum sum is 12
Cumulative sum of original array is 9
Max sum=9+12=21

{12, -5, 4, -8, 11}.
The max sum is 23 (11+12)
Inverted array, {-12,5,-4,8,-11}
Maximum sum is 9 (5+(-4)+8)
Cumulative sum of original array is 14
Max sum=14+9=23

Note:
Our array is like a ring and we have to eliminate the maximum continuous negative (i.e. the minimum sum) that implies maximum continuous positive Sum(i.e. maximum sum) in the inverted arrays.

Inversion is done to apply Kadane’s algorithm which finds the maximum sum.

Hence, the maximum sum of inverted array would be the minimum sum of the original array.

Then, we will subtract the maximum Sum of inverted array from the Sum all the elements of the original array(i.e. cumulative sum).

At last compare the max sum obtain from both the cases and print the larger one.

Kadane’s Algorithm:
Initialize:
max_so_far = 0
max_ending_here = 0

Loop for each element of the array
(a) max_ending_here = max_ending_here + a[i]
(b) 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

This will help.
If you still have doubts, feel free to ask

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

This might help you :slight_smile:

4 Likes