Max Circular Subarray Sum | Practice | GeeksforGeeks

Given an array arr[] of N integers arranged in a circular fashion. Your task is to find the maximum contiguous subarray sum.

Example 1:
Input:
N = 7
arr[] = {8,-8,9,-9,10,-11,12}
Output:
22
Explanation:
Starting from the last element
of the array, i.e, 12, and 
moving in a circular fashion, we 
have max subarray as 12, 8, -8, 9, 
-9, 10, which gives maximum sum 
as 22.
Example 2:
Input:
N = 8
arr[] = {10,-3,-4,7,6,5,-4,-1}
Output:
23
Explanation: Sum of the circular 
subarray with maximum sum is 23


Your Task:
The task is to complete the function circularSubarraySum() which returns a sum of the circular subarray with maximum sum.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

Constraints:
1 <= N <= 106
-106 <= Arr[i] <= 106
0
anil_maurya1 week ago
class Solution{
    public:
    // arr: input array
    // num: size of array
    //Function to find maximum circular subarray sum.
    int circularSubarraySum(int arr[], int num){
        int totsum=0,sum=0,mn=INT_MIN,mx=INT_MIN;
        for(int i=0;i<num;i++)
            totsum+=arr[i];
        for(int i=0;i<num;i++){
            sum+=arr[i];
            mx=max(mx,sum);
            if(sum<0) sum=0;
        }
        for(int i=0;i<num;i++)
            arr[i]=-arr[i];
        sum=0;
        for(int i=0;i<num;i++){
            sum+=arr[i];
            mn=max(mn,sum);
            if(sum<0) sum=0;
        }
        int cir=totsum+mn;
        if(cir==0)
        return mx;
        return max(cir,mx);
    }
};
0
shivi13verma1 week ago
141/142 Test Case Passed 1 failed because of Tle :
#can someone help me to make this code more opt.
def circularSubarraySum(arr,n):   ##Your code here   max_sum=kadane(arr,n)   array_sum=0   if max_sum<0:       return max_sum      for i in range(n):       array_sum+=arr[i]       arr[i]=-arr[i]   return max(array_sum+kadane(arr,n),max_sum)   def kadane(arr,n):       res=arr[0]       ending=arr[0]       for i in range(1,n):           ending=max(ending+arr[i],arr[i])           res=max(ending,res)       return res
0
shubham211019971 week ago
int kardane(int arr[],int n){
       int maxEnd=arr[0],maxi=arr[0];
       for(int i=1;i<n;i++){
           maxEnd=max(maxEnd+arr[i],arr[i]);
           maxi=max(maxi,maxEnd);
       }
       return maxi;
   } 
   int circularSubarraySum(int arr[], int n){
       
       //kadanes Algorithm
       int maxi=kardane(arr,n);
       
       if(maxi<0) return maxi;
       
       //circular Array
       int sum=0;
       for(int i=0;i<n;i++){
           sum+=arr[i];
          arr[i]=-arr[i];
       }
       int maxi2=kardane(arr,n)+sum;
       // cout<<maxi<<" "<<maxi2<<" "<<sum<<endl; 
       return max(maxi,maxi2);
       
       
   }
0
tantade20023 weeks ago
Java solutiojn
 // Your code here       int res=arr[0];       int res2=arr[0];       int sum=arr[0];       if(arr.length==1){           return arr[0];       }else{                int curr_min=arr[0];     int curr_max=arr[0];       for(int j=1;j<arr.length;j++) {  curr_max=Math.max(curr_max+arr[j], arr[j]);  res2=Math.max(res2, curr_max);   } //System.out.println(res2); for(int j=1;j<arr.length;j++) {  curr_min=Math.min(curr_min+arr[j], arr[j]);  res=Math.min(res, curr_min);  sum=sum+arr[j];      } //System.out.println(sum); //System.out.println(res);                  }        //System.out.println(sum); //System.out.println(res); //System.out.println(sum-res); if(sum-res==0){     return res2; } return(Math.max(res2,(sum-res)));   }   
0
swapniltayal4223 weeks ago
    public:   // arr: input array   // num: size of array   //Function to find maximum circular subarray sum.      int kadane(int A[], int n){       int currsum = -10000;       int bestsum = -10000;       for (int i=0; i<n; i++){           currsum = max(currsum+A[i], A[i]);           bestsum = max(currsum, bestsum);       }return bestsum;   }      int circularSubarraySum(int arr[], int num){              // your code here              if (num == 1){           return arr[0];       }if (num == 2){           int num = arr[0] + arr[1];           int num2 = max(arr[0], arr[1]);           return max(num, num2);       }              int wrapsum = -10000;       int nowrapsum = -10000;              nowrapsum = kadane(arr, num);       int total = 0;              for (int i=0; i<num; i++){           total += arr[i];           arr[i] = -arr[i];       }              wrapsum = total + kadane(arr, num);              return max(wrapsum, nowrapsum);   }
0
harshitjinodiya1 month ago
Java Solution
class Solution{
   static int circularSubarraySum(int a[], int n) {       int max_normal= normalMaxSum(a, n);       if(max_normal<0)       return max_normal;       int a_sum=0;       for(int i=0;i<n;i++)       {           a_sum+=a[i];           a[i]=-a[i];       }       int max_circular = a_sum+normalMaxSum(a, n);       return Math.max(max_normal, max_circular);   }      static int normalMaxSum(int a[], int n)   {       int res = a[0], maxEnd=a[0];       for(int i=1;i<n;i++)       {           maxEnd = Math.max(a[i], maxEnd+a[i]);           res=Math.max(res, maxEnd);       }       return res;   }}
0
parthgupta18032 months ago
  int normalMaxSum(int arr[], int n){int res = arr[0];
int maxEnding = arr[0];
for(int i = 1; i < n; i++){ maxEnding = max(maxEnding + arr[i], arr[i]);
 res = max(maxEnding, res);}return res;}   int circularSubarraySum(int arr[], int n)   {             int max_normal = normalMaxSum(arr, n);
if(max_normal < 0) return max_normal;
int arr_sum = 0;
for(int i = 0; i < n; i++){ arr_sum += arr[i];
 arr[i] = -arr[i];}
int max_circular = arr_sum + normalMaxSum(arr, n);
return max(max_circular, max_normal);}
 
0
hamidnourashraf2 months ago
import math
def max_sub_arary(arr, n):
        max_sum = -math.inf
        _sum = 0
        for i in range(0,n):
            _sum += arr[i]
            max_sum = max(max_sum, _sum)
            if _sum < 0:
                _sum = 0
        return max_sum
        
def min_sub_array(arr, n):
        min_sum = math.inf
        _sum = 0
        for i in range(0,n):
            _sum += arr[i]
            min_sum = min(min_sum, _sum)
            if _sum > 0:
                _sum = 0
        return min_sum 
        
def circularSubarraySum(arr,n):
    arr_sum = sum(arr)
    max_sub_arry_sum = max_sub_arary(arr, n)
    min_sub_arry_sum = min_sub_array(arr, n)
    
    if arr_sum - min_sub_arry_sum == 0: --> all negative in arr
        return max_sub_arry_sum
    return max(max_sub_arry_sum, arr_sum-min_sub_arry_sum)
+1
kartikeyashokgautam2 months ago
JAVA Solution:-
    static int circularSubarraySum(int a[], int n) {              int total = 0, maxSum = a[0], curMax = 0, minSum = a[0], curMin = 0;       for (int x : a) {           curMax = Math.max(curMax + x, x);           maxSum = Math.max(maxSum, curMax);           curMin = Math.min(curMin + x, x);           minSum = Math.min(minSum, curMin);           total += x;       }       return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum;      }
 
0
ldeepak112 months ago
/**
     * Standard Kadane's Algorithm
    */
    int maxSumOfNormalSubArray(int arr[], int n) {
        int currSum=arr[0];
        int currMax=arr[0];
        for (int i=1; i<n; i++) {
            currSum=max(currSum+arr[i], arr[i]);
            currMax=max(currMax, currSum);
        }
        return currMax;
    }
    
    /**
     * maxSumOfCircularSubarray=TotalSum - minSumOfNormalSubarray
     * maxSumOfCircularSubarray=TotalSum + maxSumOfInvertedSubarray
    */
    int maxSumOfCircularSubarray(int arr[], int n) {
        /**
         * Computing total sum of the array, also inverting the array values.
        */
        int totalSum=0;
        for (int i=0; i<n; i++) {
            totalSum+=arr[i];
            arr[i]=-arr[i];
        }
        
        return totalSum+maxSumOfNormalSubArray(arr, n);
    }
    
    // arr: input array
    // num: size of array
    //Function to find maximum circular subarray sum.
    int circularSubarraySum(int arr[], int num){
        // your code here
        
        /**
         * Two Cases: 
         * 1. When the maximum subarray is not circular
         * 2. When the maximum subarray is circular.
         * Answer would be max of case 1 and case 2
        */
        int a=maxSumOfNormalSubArray(arr, num);
        int b=maxSumOfCircularSubarray(arr, num);
        
        /**
         * Corner case: When all elements are -ve.
         * maxSumOfNormalSubArray = max(arr), and it will be -ve
         * maxSumOfCircularSubarray = TotalSum - minSumOfNormalSubarray
         * minSumOfNormalSubarray = sum(arr), adding all the -ve elements would give us the minimum sum
         * 
         * => maxSumOfCircularSubarray = TotalSum - sum(arr)
         * Since TotalSum == sum(arr) 
         * => maxSumOfCircularSubarray = 0
         * Which means sum of an empty subarray. This is wrong as empty subarrays are not allowed.
         * 
        */
        if (a<0) {
           return a; 
        }
        else {
            return max(a, b);    
        }
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.