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 + ai 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
Top comments (0)