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
saipraveensura12348 hours ago
can someone explain error in this code
 
 
 
class Solution{
    public:
    // arr: input array
    // num: size of array
    //Function to find maximum circular subarray sum.
    int circularSubarraySum(int arr[], int num){
        int res1=arr[0],maxending=arr[0];
        int res2=arr[0],minending=arr[0];
        int arrsum=0;
        for(int i=1;i<num;i++)
        {
            arrsum=arrsum+arr[i];
            maxending=max(maxending+arr[i],arr[i]);
            res1=max(res1,maxending);
            minending=min(minending+arr[i],arr[i]);
            res2=min(minending,res2);
        }
        res2=arrsum-(res2);
        
        return max(res1,res2);
        
        // your code here
    }
};
0
abhinayabhi14119 hours ago
   int result=INT_MAX;      int r=INT_MIN;      int sum1=0,sum2=0,sum3=0;      for(int i=0;i<num;i++)      {          sum1+=arr[i];          sum2+=arr[i];          sum3+=arr[i];          sum3=max(sum3,arr[i]);          r=max(r,sum3);          sum1=min(sum1,arr[i]);          result=min(result,sum1);      }      if(r<0)      return r;      return max(sum2-result,r);
+1
yashurawat190321 hours ago
WELL EXPLAINED
PLS UPVOTE
 
 
 
    int kadanes(int arr[],int n)   {       int currSum = 0;       int maxSum = INT_MIN;       for(int i=0;i<n;i++)       {           currSum = max(arr[i] + currSum, arr[i]);           maxSum = max(maxSum,currSum);       }       return maxSum;   }   int circularSubarraySum(int arr[], int n){              // your code here       int x = kadanes(arr,n);       int y =0;       for(int i =0;i<n;i++)       {           y += arr[i];           arr[i] = -arr[i];//here we are calculating min sub array        }                    //by changing sign so that min subarray became max sub array        int z = kadanes(arr,n);//z is maxsub array after changing sign       if(y-(-z)==0)//and then subtract total sum (y) with negative of z       {           return x;       }       return max(x,y-(-z));   }
0
abhishek0908022 days ago
int kadanes(int arr[],int n)
    {
        int ans=INT_MIN; int sum=0; 
        for(int i=0;i<n;i++)
        {
            sum+=arr[i]; 
            if(sum>ans)
            ans=sum; 
            if(sum<0) sum=0;
        }
        return ans;
    }
    int circularSubarraySum(int arr[], int num){
        int x=kadanes(arr,num); int sum=0; 
        for(int i=0;i<num;i++)
       {  sum+=arr[i]; arr[i]=-1*arr[i];}
        int y=kadanes(arr,num); 
        int z=sum+y; 
        if(z==0) return x; 
        return max(z,x); 
        
    }
0
ruchikajamwal03192 days ago
class Solution{   public:   // arr: input array   // num: size of array   //Function to find maximum circular subarray sum.   int circularSubarraySum(int arr[], int num){              // your code here       int result=INT_MAX;      int r=INT_MIN;      int sum1=0,sum2=0,sum3=0;      for(int i=0;i<num;i++)      {          sum1+=arr[i];          sum2+=arr[i];          sum3+=arr[i];          sum3=max(sum3,arr[i]);          r=max(r,sum3);          sum1=min(sum1,arr[i]);          result=min(result,sum1);      }      if(r<0)      return r;      return max(sum2-result,r);
          }};
0
mrharshkshitij90603 days ago
 
class Solution{
 public:
      int totalsum(int arr[], int n)
   {
       int res=arr[0];
       int maxend=arr[0];
       for(int i=1; i<n; i++)
       {
           maxend= max(maxend+arr[i], arr[i]);
           res=max(res, maxend);
       }
       return res;
   }
   
   int circularSubarraySum(int arr[], int num)
   {
       int total=totalsum(arr, num);
       if(total<0)
          return total;
       
       int sum=0;
       for(int i=0; i<num; i++)
       {
           sum=sum+arr[i];
           arr[i]= -arr[i];
       }
        int max_cir= sum+totalsum(arr, num);
        return max(max_cir, total);
   }
};
 
+2
amankrguptagumla1441 week ago
//JAVA SOLUTION
class Solution{
   static int normalMaxSum(int arr[], int n)
   {
    int res = arr[0];
    int maxEnding = arr[0];
    for(int i = 1; i < n; i++)
    {
     maxEnding = Math.max(maxEnding + arr[i], arr[i]);
     res = Math.max(maxEnding, res);
    }
    
    return res;
   }
   // a: input array
   // n: size of array
   //Function to find maximum circular subarray sum.
   static int circularSubarraySum(int arr[], int n) {
       
       // Your code here
       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 Math.max(max_circular, max_normal);
    
       //return Integer.max(kadane(arr,n), reverseKadane(arr,n));
   }
   
}

+1
ayushsunariya4581 week ago
C++ Easy Solution
Logic: So there are two case.Case 1. The first is that the subarray take only a middle part, and we know how to find the max subarray sum.Case2. The second is that the subarray take a part of head array and a part of tail array.We can transfer this case to the first one.The maximum result equals to the total sum minus the minimum subarray sum. 
	int circularSubarraySum(int A[], int n){
        
        // your code here
        int total = 0, maxSum = A[0], curMax = 0, minSum = A[0], curMin = 0;
        for (int i=0;i<n;i++) {
            curMax = max(curMax + A[i], A[i]);
            maxSum = max(maxSum, curMax);
            curMin = min(curMin + A[i], A[i]);
            minSum = min(minSum, curMin);
            total += A[i];
        }
        return maxSum > 0 ? max(maxSum, total - minSum) : maxSum;
    }
0
prathameshmistry2 weeks ago
C++++
 
 
 
class Solution{   public:   //Function to find maximum circular subarray sum.   int circularSubarraySum(int a[], int n)    {        bool flag  = false;       int count =0;int maxx = INT_MIN;       for(int i = 0; i < n; i++)       {           //Storing the maximum element in the array.           if(a[i] > maxx)             maxx = a[i];           //Counting total number of negative numbers in the array.             if(a[i] < 0)             count++;       }       if(count == n)         return maxx;           //Case 1:We get the maximum sum using standard Kadane's algorithm.     int max_kadane = kadane(a, n);         //Case 2:We now find the maximum sum that includes corner elements.     int max_wrap = 0, i;     for (i = 0; i < n; i++)     {             //Calculating total sum of array elements.      max_wrap += a[i];       //Inverting the sign of array elements.      a[i] = -a[i];      }         //Maximum sum with corner elements will be:     //Total sum of array elements-(-max subarray sum after changing     //sign of array elements).     max_wrap = max_wrap + kadane(a, n);         //The maximum circular subarray sum will be maximum of two sums.     return (max_wrap > max_kadane)? max_wrap: max_kadane;    }       //Standard Kadane's algorithm to find maximum subarray sum.   int kadane(int a[], int n)    {     int max_so_far = 0, max_ending_here = 0;     int i;     for (i = 0; i < n; i++)     {         //Storing max sum till current index.     max_ending_here = max_ending_here + a[i];      //If max sum till current index is negative, we update it to 0.     if (max_ending_here < 0)       max_ending_here = 0;         //Storing the max sum so far.     if (max_so_far < max_ending_here)       max_so_far = max_ending_here;     }     return max_so_far;    } };
0
gopikrishnaguntamukkala32 weeks ago
python code
ALL TEST CASES PASSED

def circularSubarraySum(arr,n):
    ##Your code here
    def kadane(num):
        sumtillnow=num[0]
        totalsum=num[0]
        for i in num[1:]:
            sumtillnow=max(i,sumtillnow+i)
            totalsum=max(totalsum,sumtillnow)
        return totalsum
    t=kadane(arr)
    sum1=0
    for i in range(n):
        sum1+=arr[i]
        arr[i]=-arr[i]
    sum1+=kadane(arr)
    if sum1>t and sum1!=0:
        return sum1
    else:
        return t
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.