Maximum Circular Subarray Sum
Last Updated :
22 Jul, 2025
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 may wrap around the end and continue from the beginning, forming a circular segment.
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));
[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));
[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 = 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));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem