Open In App

Maximum Circular Subarray Sum

Last Updated : 26 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given a circular array arr[], find the maximum sum of any non-empty subarray. A circular array allows wrapping from the end back to the beginning.
Note: A subarray can span from the end of the array and continue at the beginning.

Examples: 

Input: arr[] = [8, -8, 9, -9, 10, -11, 12]
Output: 22
Explanation: The circular subarray [12, 8, -8, 9, -9, 10] gives the maximum sum, which is 22.

Input: arr[] = [4, -1, -2, 3]
Output: 7
Explanation: The circular subarray [3, 4] gives the maximum sum of 7.

Input: arr[] = [5, -2, 3, 4]
Output: 12
Explanation: The circular subarray [3, 4, 5] gives the maximum sum of 12.

[Naive Approach] Considering All Possible Subarrays – O(n^2) Time and O(1) Space

The idea is to consider every element as the beginning of the subarray, and calculate the maximum possible sum, which includes both circular and linear subarrays starting from that element.

C++
#include <iostream>
#include <vector>
using namespace std;

int maxCircularSum(vector<int> &arr) {
    int n = arr.size();
    int res = arr[0];
    
    // Subarray that starts with index i
    for(int i = 0; i < n; i++) {
        int currSum = 0;
        
        // Considering all possible endpoints of the 
        // Subarray that begins with index i
        for(int j = 0; j < n; j++) {
            
            // Circular index
            int idx = (i + j) % n;
            currSum = currSum + arr[idx];            
            res = max(res, currSum);
        }
    }
    
    return res;
}

int main() {
	vector<int> arr = {8, -8, 9, -9, 10, -11, 12};
	cout << maxCircularSum(arr);
}
C
#include <stdio.h>

int maxCircularSum(int arr[], int n) {
    
    int res = arr[0];
    
    // Subarray that starts with index i
    for(int i = 0; i < n; i++) {
        int currSum = 0;
        
        // Considering all possible endpoints of the 
        // Subarray that begins with index i
        for(int j = 0; j < n; j++) {
            
            // Circular index
            int idx = (i + j) % n;
            currSum = currSum + arr[idx];            
            if (currSum > res) {
                res = currSum;
            }
        }
    }
    
    return res;
}

int main() {
    int arr[] = {8, -8, 9, -9, 10, -11, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", maxCircularSum(arr, n));
    return 0;
}
Java
class GfG {
    
    static int maxCircularSum(int[] arr) {
    
        int n = arr.length;
        int res = arr[0];
        
        // Subarray that starts with index i
        for(int i = 0; i < n; i++) {
            int currSum = 0;
            
            // Considering all possible endpoints of the 
            // Subarray that begins with index i
            for(int j = 0; j < n; j++) {
                
                // Circular index
                int idx = (i + j) % n;
                currSum = currSum + arr[idx];            
                res = Math.max(res, currSum);
            }
        }
        
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {8, -8, 9, -9, 10, -11, 12};
        System.out.println(maxCircularSum(arr));
    }
}
Python
def maxCircularSum(arr):
    
    n = len(arr)
    res = arr[0]
    
    # Subarray that starts with index i
    for i in range(n):
        currSum = 0
        
        # Considering all possible endpoints of the 
        # Subarray that begins with index i
        for j in range(n):
            
            # Circular index
            idx = (i + j) % n
            currSum += arr[idx]            
            res = max(res, currSum)
    
    return res
    
if __name__ == "__main__":
    
    arr = [8, -8, 9, -9, 10, -11, 12]
    print(maxCircularSum(arr))
    
C#
using System;

class GfG {
    
    static int maxCircularSum(int[] arr) {
    
        int n = arr.Length;
        int res = arr[0];
        
        // Subarray that starts with index i
        for(int i = 0; i < n; i++) {
            int currSum = 0;
            
            // Considering all possible endpoints of the 
            // Subarray that begins with index i
            for(int j = 0; j < n; j++) {
                
                // Circular index
                int idx = (i + j) % n;
                currSum = currSum + arr[idx];            
                res = Math.Max(res, currSum);
            }
        }
        
        return res;
    }

    static void Main() {
        int[] arr = {8, -8, 9, -9, 10, -11, 12};
        Console.WriteLine(maxCircularSum(arr));
    }
}
JavaScript
function maxCircularSum(arr) {
    const n = arr.length;
    let res = arr[0];
    
    // Subarray that starts with index i
    for(let i = 0; i < n; i++) {
        let currSum = 0;
        
        // Considering all possible endpoints of the 
        // Subarray that begins with index i
        for(let j = 0; j < n; j++) {
            
            // Circular index
            const idx = (i + j) % n;
            currSum += arr[idx];            
            res = Math.max(res, currSum);
        }
    }
    
    return res;
}

// Driver Code
const arr = [8, -8, 9, -9, 10, -11, 12];
console.log(maxCircularSum(arr));

Output
22

[Better Approach] Using Prefix and Suffix Sum – O(n) Time and O(n) Space

In a circular array, the maximum subarray sum can be either the maximum normal sum, which is the highest sum of a non-circular array, or the maximum circular sum, which includes elements from both the start and the end of the array. The normal sum can be efficiently calculated using Kadane's algorithm. And, the circular sum is calculated by combining prefix sum and suffix sum.

  • First, we will compute the maxSuffix array, where maxSuffix[i] stores the maximum suffix sum starting from any index >= i.
  • Then, as we iterate through the input array, we combine the prefix sum up to index i with the maxSuffix value at index i + 1 (to avoid double-counting the ith element) to calculate circular sum and take the maximum for all values of i.
C++
#include <iostream>
#include <vector>
using namespace std;

int maxCircularSum(vector<int> &arr) {
    int n = arr.size();
    int suffixSum = arr[n - 1];
    
    // maxSuffix array to store the value of 
    // maximum suffix occured so far.
    vector<int> maxSuffix(n + 1, 0);
    maxSuffix[n - 1] = arr[n - 1];
    
    for(int i = n - 2; i >= 0; i--) {
        suffixSum = suffixSum + arr[i];
        maxSuffix[i] = max(maxSuffix[i + 1], suffixSum);
    }
    
    // circularSum is Maximum sum of circular subarray
    int circularSum = arr[0];
    
    // normalSum is Maxium sum subarray considering 
    // the array is non-circular
    int normalSum = arr[0];
    
    int currSum = 0;
    int prefix = 0;
    
    for(int i = 0; i < n; i++) {
        
        // Kadane's algorithm
        currSum = max(currSum + arr[i], arr[i]);
        normalSum = max(normalSum, currSum);
      
		// Calculating maximum Circular Sum
        prefix = prefix + arr[i];
        circularSum = max(circularSum, prefix + maxSuffix[i+1]);
    }
    
    return max(circularSum, normalSum);
}

int main() {
	vector<int> arr = {8, -8, 9, -9, 10, -11, 12};
	cout << maxCircularSum(arr);
}
C
#include <stdio.h>

int maxCircularSum(int arr[], int n) {
    int suffixSum = arr[n - 1];

    // maxSuffix array to store the value of 
    // maximum suffix occurred so far.
    int* maxSuffix = (int*)malloc((n + 1) * sizeof(int));
    maxSuffix[n - 1] = arr[n - 1];

    for(int i = n - 2; i >= 0; i--) {
        suffixSum = suffixSum + arr[i];
        if(maxSuffix[i + 1] > suffixSum)
        	maxSuffix[i] = maxSuffix[i + 1];
        else 
            maxSuffix[i] = suffixSum;
    }

    // circularSum is Maximum sum of circular subarray
    int circularSum = arr[0];

    // normalSum is Maximum sum subarray considering 
    // the array is non-circular
    int normalSum = arr[0];

    int currSum = 0;
    int prefix = 0;

    for(int i = 0; i < n; i++) {
        
        // Kadane's Algorithm
        currSum = (currSum + arr[i] > arr[i]) ? currSum + arr[i] : arr[i];
        normalSum = (normalSum > currSum) ? normalSum : currSum;
      
		// Calculating Maximum Circular Sum
        prefix = prefix + arr[i];
        if(circularSum < prefix + maxSuffix[i + 1])
          	circularSum = prefix + maxSuffix[i + 1];
    }

    return (circularSum > normalSum) ? circularSum : normalSum;
}

int main() {
    int arr[] = {8, -8, 9, -9, 10, -11, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", maxCircularSum(arr, n));
    return 0;
}
Java
import java.util.Arrays;

class GfG {
    
    static int maxCircularSum(int[] arr) {
        
        int n = arr.length;
        int suffixSum = arr[n - 1];

        // maxSuffix array to store the value of 
        // maximum suffix occurred so far.
        int[] maxSuffix = new int[n + 1];
        maxSuffix[n - 1] = arr[n - 1];

        for(int i = n - 2; i >= 0; i--) {
            suffixSum = suffixSum + arr[i];
            maxSuffix[i] = Math.max(maxSuffix[i + 1], suffixSum);
        }

        // circularSum is Maximum sum of circular subarray
        int circularSum = arr[0];

        // normalSum is Maximum sum subarray considering 
        // the array is non-circular
        int normalSum = arr[0];

        int currSum = 0;
        int prefix = 0;

        for(int i = 0; i < n; i++) {
            
            // Kadane's algorithm
            currSum = Math.max(currSum + arr[i], arr[i]);
            normalSum = Math.max(normalSum, currSum);
          
			// Calculating maximum Circular Sum
            prefix = prefix + arr[i];
            circularSum = Math.max(circularSum, prefix + maxSuffix[i + 1]);
        }

        return Math.max(circularSum, normalSum);
    }

    public static void main(String[] args) {
        int[] arr = {8, -8, 9, -9, 10, -11, 12};
        System.out.println(maxCircularSum(arr));
    }
}
Python
def maxCircularSum(arr):
    
    n = len(arr)
    suffixSum = arr[n - 1]

    # maxSuffix array to store the value of 
    # maximum suffix occurred so far.
    maxSuffix = [0] * (n + 1)
    maxSuffix[n - 1] = arr[n - 1]

    for i in range(n - 2, -1, -1):
        suffixSum += arr[i]
        maxSuffix[i] = max(maxSuffix[i + 1], suffixSum)

    # circularSum is Maximum sum of circular subarray
    circularSum = arr[0]

    # normalSum is Maximum sum subarray considering 
    # the array is non-circular
    normalSum = arr[0]

    currSum = 0
    prefix = 0

    for i in range(n):
        
        # Kadane's algorithm
        currSum = max(currSum + arr[i], arr[i])
        normalSum = max(normalSum, currSum)
        
		# Calculating maximum Circular Sum
        prefix += arr[i]
        circularSum = max(circularSum, prefix + maxSuffix[i + 1])

    return max(circularSum, normalSum)

if __name__ == "__main__":
        
    arr = [8, -8, 9, -9, 10, -11, 12]
    print(maxCircularSum(arr))
C#
using System;

class GfG {
    static int maxCircularSum(int[] arr) {
        int n = arr.Length;
        int suffixSum = arr[n - 1];

        // maxSuffix array to store the value of 
        // maximum suffix occurred so far.
        int[] maxSuffix = new int[n + 1];
        maxSuffix[n - 1] = arr[n - 1];

        for(int i = n - 2; i >= 0; i--) {
            suffixSum = suffixSum + arr[i];
            maxSuffix[i] = Math.Max(maxSuffix[i + 1], suffixSum);
        }

        // circularSum is Maximum sum of circular subarray
        int circularSum = arr[0];

        // normalSum is Maximum sum subarray considering 
        // the array is non-circular
        int normalSum = arr[0];

        int currSum = 0;
        int prefix = 0;

        for(int i = 0; i < n; i++) {
            
            // Kadane's algorithm
            currSum = Math.Max(currSum + arr[i], arr[i]);
            normalSum = Math.Max(normalSum, currSum);
          
			// Calculating maximum Circular Sum
            prefix = prefix + arr[i];
            circularSum = Math.Max(circularSum, prefix + maxSuffix[i + 1]);
        }

        return Math.Max(circularSum, normalSum);
    }

    static void Main() {
        int[] arr = {8, -8, 9, -9, 10, -11, 12};
        Console.WriteLine(maxCircularSum(arr));
    }
}
JavaScript
function maxCircularSum(arr) {
    let n = arr.length;
    let suffixSum = arr[n - 1];

    // maxSuffix array to store the value of 
    // maximum suffix occurred so far.
    let maxSuffix = new Array(n + 1).fill(0);
    maxSuffix[n - 1] = arr[n - 1];

    for(let i = n - 2; i >= 0; i--) {
        suffixSum += arr[i];
        maxSuffix[i] = Math.max(maxSuffix[i + 1], suffixSum);
    }

    // circularSum is Maximum sum of circular subarray
    let circularSum = arr[0];

    // normalSum is Maximum sum subarray considering 
    // the array is non-circular
    let normalSum = arr[0];

    let currSum = 0;
    let prefix = 0;

    for(let i = 0; i < n; i++) {
        
        // Kadane's algorithm
        currSum = Math.max(currSum + arr[i], arr[i]);
        normalSum = Math.max(normalSum, currSum);

        // Calculating maximum Circular Sum
        prefix += arr[i];
        circularSum = Math.max(circularSum, prefix + maxSuffix[i + 1]);
    }

    return Math.max(circularSum, normalSum);
}

// Driver Code
const arr = [8, -8, 9, -9, 10, -11, 12];
console.log(maxCircularSum(arr));

Output
22

[Expected Approach] Using Kadane's Algorithm – O(n) Time and O(1) Space

This approach is similar to the previous one, but the key difference is that we're using Kadane's algorithm to find the circular subarray sum as well. The maximum sum of a circular subarray can be defined as the total sum of the array minus the sum of a subarray in the middle. So, to maximize the circular subarray sum, we need to minimize the subarray sum.

Maximum-circular-subarray-sum
  • Maximum Circular Subarray Sum =Total Sum - Minimum Subarray Sum.
  • If the minimum subarray sum equals the total sum of the array, we return the normal maximum subarray sum, because if all elements are negative, the circular sum would be zero, but the answer will be negative only.
C++
#include <iostream>
#include <vector>
using namespace std;

int maxCircularSum(vector<int> &arr) {

    int totalSum = 0;
    int currMaxSum = 0, currMinSum = 0;
    int maxSum = arr[0], minSum = arr[0];

    for (int i = 0; i < arr.size(); i++) {

        // Kadane's to find maximum sum subarray
        currMaxSum = max(currMaxSum + arr[i], arr[i]);
        maxSum = max(maxSum, currMaxSum);

        // Kadane's to find minimum sum subarray
        currMinSum = min(currMinSum + arr[i], arr[i]);
        minSum = min(minSum, currMinSum);

        // Sum of all the elements of input array
        totalSum = totalSum + arr[i];
    }

    int normalSum = maxSum;
    int circularSum = totalSum - minSum;

    // If the minimum subarray is equal to total Sum
    // then we just need to return normalSum
    if (minSum == totalSum)
        return normalSum;

    return max(normalSum, circularSum);
}

int main() {
    vector<int> arr = {8, -8, 9, -9, 10, -11, 12};
    cout << maxCircularSum(arr);
}
C
#include <stdio.h>

int maxCircularSum(int arr[], int n) {
    int totalSum = 0;    
    int currMaxSum = 0, currMinSum = 0;
    int maxSum = arr[0], minSum = arr[0];
    
    for(int i = 0; i < n; i++) {
      
        // Kadane's to find maximum sum subarray
        currMaxSum = (currMaxSum + arr[i] > arr[i]) ? 
          					currMaxSum + arr[i] : arr[i];
        maxSum = (maxSum > currMaxSum) ? maxSum : currMaxSum; 
        
        // Kadane's to find minimum sum subarray
        currMinSum = (currMinSum + arr[i] < arr[i]) ? 
          						currMinSum + arr[i] : arr[i];
        minSum = (minSum < currMinSum) ? minSum : currMinSum;
        
        // Sum of all the elements of input array
        totalSum += arr[i];
    }
    
    int normalSum = maxSum;
    int circularSum = totalSum - minSum;
    
    // If the minimum subarray is equal to total Sum
    // then we just need to return normalSum
    if(minSum == totalSum)
        return normalSum;
    
    return (normalSum > circularSum) ? normalSum : circularSum;
}

int main() {
    int arr[] = {8, -8, 9, -9, 10, -11, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", maxCircularSum(arr, n));
    return 0;
}
Java
class GfG {

    static int maxCircularSum(int[] arr) {
        
        int totalSum = 0;    
        int currMaxSum = 0, currMinSum = 0;
        int maxSum = arr[0], minSum = arr[0];
        
        for(int i = 0; i < arr.length; i++) {
          
            // Kadane's to find maximum sum subarray
            currMaxSum = Math.max(currMaxSum + arr[i], arr[i]);
            maxSum = Math.max(maxSum, currMaxSum); 
          
            // Kadane's to find minimum sum subarray
            currMinSum = Math.min(currMinSum + arr[i], arr[i]);
            minSum = Math.min(minSum, currMinSum);
            
            // Sum of all the elements of input array
            totalSum += arr[i];
        }
        
        int normalSum = maxSum;
        int circularSum = totalSum - minSum;
        
        // If the minimum subarray is equal to total Sum
        // then we just need to return normalSum
        if(minSum == totalSum)
            return normalSum;
        
        return Math.max(normalSum, circularSum);
    }

    public static void main(String[] args) {
        int[] arr = {8, -8, 9, -9, 10, -11, 12};
        System.out.println(maxCircularSum(arr));
    }
}
Python
def maxCircularSum(arr):
    
    totalSum = 0    
    currMaxSum = 0
    currMinSum = 0
    maxSum = arr[0]
    minSum = arr[0]
    
    for i in range(len(arr)):
      
        # Kadane's to find maximum sum subarray
        currMaxSum = max(currMaxSum + arr[i], arr[i])
        maxSum = max(maxSum, currMaxSum) 
        
        # Kadane's to find minimum sum subarray
        currMinSum = min(currMinSum + arr[i], arr[i])
        minSum = min(minSum, currMinSum)
        
        # Sum of all the elements of input array
        totalSum += arr[i]
    
    normalSum = maxSum
    circularSum = totalSum - minSum
    
    # If the minimum subarray is equal to total Sum
    # then we just need to return normalSum
    if minSum == totalSum:
        return normalSum
    
    return max(normalSum, circularSum)

if __name__ == "__main__":
    
    arr = [8, -8, 9, -9, 10, -11, 12]
    
    print(maxCircularSum(arr))
C#
using System;

class GfG {
    
    static int maxCircularSum(int[] arr) {
        
        int totalSum = 0;    
        int currMaxSum = 0, currMinSum = 0;
        int maxSum = arr[0], minSum = arr[0];
        
        for(int i = 0; i < arr.Length; i++) {
          
            // Kadane's to find maximum sum subarray
            currMaxSum = Math.Max(currMaxSum + arr[i], arr[i]);
            maxSum = Math.Max(maxSum, currMaxSum); 
          
            // Kadane's to find minimum sum subarray
            currMinSum = Math.Min(currMinSum + arr[i], arr[i]);
            minSum = Math.Min(minSum, currMinSum);
            
            // Sum of all the elements of input array
            totalSum += arr[i];
        }
        
        int normalSum = maxSum;
        int circularSum = totalSum - minSum;
        
        // If the minimum subarray is equal to total Sum
        // then we just need to return normalSum
        if(minSum == totalSum)
            return normalSum;
        
        return Math.Max(normalSum, circularSum);
    }

    static void Main() {
        int[] arr = {8, -8, 9, -9, 10, -11, 12};
        Console.WriteLine(maxCircularSum(arr));
    }
}
JavaScript
function maxCircularSum(arr) {
    
    let totalSum = 0;
    let currMaxSum = 0, currMinSum = 0;
    let maxSum = arr[0], minSum = arr[0];

    for (let i = 0; i < arr.length; i++) {

        // Kadane's to find maximum sum subarray
        currMaxSum = Math.max(currMaxSum + arr[i], arr[i]);
        maxSum = Math.max(maxSum, currMaxSum);

        // Kadane's to find minimum sum subarray
        currMinSum = Math.min(currMinSum + arr[i], arr[i]);
        minSum = Math.min(minSum, currMinSum);

        // Sum of all the elements of input array
        totalSum += arr[i];
    }

    let normalSum = maxSum;
    let circularSum = totalSum - minSum;

    // If the minimum subarray is equal to total Sum
    // then we just need to return normalSum
    if (minSum === totalSum)
        return normalSum;

    return Math.max(normalSum, circularSum);
}

// Driver Code
const arr = [ 8, -8, 9, -9, 10, -11, 12 ];
console.log(maxCircularSum(arr));

Output
22

Next Article
Practice Tags :

Similar Reads