Given a circular integer array, find a subarray with the largest sum in it.

For example,

Input:  {2, 1, -5, 4, -3, 1, -3, 4, -1}
 
Output: Subarray with the largest sum is {4, -1, 2, 1} with sum 6.
 
 
Input:  {-3, 1, -3, 4, -1, 2, 1, -5, 4}
 
Output: Subarray with the largest sum is {4, -1, 2, 1} with sum 6.

Practice this problem

The problem differs from the problem of finding the maximum sum circular subsequence. Unlike subsequences, subarrays are required to occupy consecutive positions within the original array.

 
The idea is to find the sequence which will have a maximum negative value. If we remove that minimum sum sequence from the input sequence, we will be left with the maximum sum circular sequence. Finally, return the maximum of the maximum-sum circular sequence (includes corner elements) and maximum-sum non-circular sequence.

For example, consider array {2, 1, -5, 4, -3, 1, -3, 4, -1}. The sequence having maximum negative value is {-5, 4, -3, 1, -3}, i.e., -6. If we remove this minimum sum sequence from the array, we will get the maximum sum circular sequence, i.e., {2, 1, 4, -1} having sum 6. Since the maximum sum circular sequence is greater than the maximum sum non-circular sequence, i.e., {4} for the given array, it is the answer.

 
We can find the maximum-sum non-circular sequence in linear time by using Kadane’s algorithm. We can find a maximum-sum circular sequence by inverting the sign of all array elements and then applying Kadane’s algorithm.

For example, if we invert signs of array {2, 1, -5, 4, -3, 1, -3, 4, -1}, we get {-2, -1, 5, -4, 3, -1, 3, -4, 1} which has maximum sum sequence {5, -4, 3, -1, 3} having sum 6. Now inverting the signs back, we get a minimum sum sequence {-5, 4, -3, 1, -3} having sum -6. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The sum of the subarray with the largest sum is 6

Java


Download  Run Code

Output:

The sum of the subarray with the largest sum is 6

Python


Download  Run Code

Output:

The sum of the sublist with the largest sum is 6

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.