Kadane's Algorithm | Practice | GeeksforGeeks

Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number) which has the maximum sum and return its sum.

Example 1:
Input:
N = 5
Arr[] = {1,2,3,-2,5}
Output:
9
Explanation:
Max subarray sum is 9
of elements (1, 2, 3, -2, 5) which 
is a contiguous subarray.

Example 2:
Input:
N = 4
Arr[] = {-1,-2,-3,-4}
Output:
-1
Explanation:
Max subarray sum is -1 
of element (-1)

Your Task:
You don't need to read input or print anything. The task is to complete the function maxSubarraySum() which takes Arr[] and N as input parameters and returns the sum of subarray with maximum sum.

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

Constraints:
1 ≤ N ≤ 106
-107 ≤ A[i] ≤ 107
0
shreyapanwar71211 hours ago
My soltn:
 long long maxSubarraySum(int arr[], int n){       long long maxS=0;       long long currS=0;       for(int i=0;i<n;i++){           currS+=arr[i];           if(currS>maxS){           maxS=currS;           }           if(currS<0){               currS=0;           }       }       return maxS;      }
error:
prog.cpp:49:1: error: expected } at end of input } ^ prog.cpp:49:1: error: expected unqualified-id at end of input
 
Q. How am I supposed to solve this if it shows the error in driver code? What have I done wrong?
 
 
0
shreyapanwar712
This comment was deleted.
0
sangrambachu1 day ago
To support all -ve number we need to use Math.max()
 
long maxSubarraySum(int arr[], int n){
        
        // Your code here
        long max = arr[0];
        long current = arr[0];
        
        for(int i=1; i<n; i++) {
            current = Math.max(arr[i], current+arr[i]);
            
            if(current > max) {
                max = current;
            }
        }
        
        return max;
    }
0
ianupmondal2 days ago
Easy Java solution:
 
long maxSubarraySum(int arr[], int n){       long maxSum=Integer.MIN_VALUE;       long currSum = 0;       for (int i=0; i<n; i++){           currSum += arr[i];               if(currSum>maxSum)                   maxSum=currSum;               if(currSum<0)                   currSum=0;       }       return maxSum;   }
0
salamromim5 days ago
 //Function to find the sum of contiguous subarray with    public long maxSubarraySum(int[] arr, int n)   {       //code intinhere       int curmax=0;       int max=int.MinValue;    //   max=0;              for(int i=0;i<n;i++)       {       curmax=arr[i]+curmax;              if (curmax<arr[i])        {     curmax=Math.Max(arr[i],curmax);       if(max<curmax)     {     max=curmax;     }       }       else       {                  if(curmax>arr[i])       curmax=Math.Max(arr[i],curmax);     //  else     //  curmax=Math.Min(arr[i],curmax)
       if(max<curmax)       max=curmax;       }   }       return max;      }
}
0
surabhichoubey556 days ago
i was trying to solve this question without using kadanes algo ........please tell me where my logic fails explain me please it giving me output  11   
 
long long maxSubarraySum(int arr[], int n){              // Your code here   long long sum = 0;   long long currentSum = 0;   int current = 0;   long long ans = 0;   for(int i = 0;i<n;i++)   {       sum+= arr[i];   }      while(current<n)   {       ans = max(sum,currentSum);       currentSum = sum-arr[current];       current++;   }   if(ans<-1)   {       return -1;   }   return ans;          }
0
prasantpoudel331 week ago
max_so_far =arr[0]
curr_max = arr[0]
     
for i in range(1,N):
     curr_max = max(arr[i], curr_max + arr[i])
     max_so_far = max(max_so_far,curr_max)
return max_so_far
 
+1
ligghhts1 week ago
    long long maxSubarraySum(int arr[], int n){              // Your code here       long long int ans = 0;       long long int max = INT_MIN;       for(int i = 0;i < n;i++){           ans += arr[i];           if(ans > max)max = ans;           if(ans < 0)ans = 0;       }       return max;   }
+1
illiyazzr1 week ago
C++ (Brute Force) Solution | inside main() function
 
#include <vector>#include <iostream>
using namespace std;
int main(){   vector<int>vec;   int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};   int s = sizeof(arr)/sizeof(arr[0]);   int sum=0;      for(int i=0;i<s;i++){      for(int j=i;j<s;j++){         sum+=arr[j];         vec.push_back(sum);      }      sum=0;   }   int finalSum=vec[0];   for(int i=0;i<vec.size();i++){      if(vec[i]>finalSum){         finalSum=vec[i];      }   }   cout<<"Longest contiguous sub-array sum : "<<finalSum;}
 
0
prathamsinghal1 week ago
Great Technique to solve the Problem.Tutorial Link: 
class Solution{

    // arr: input array
    // n: size of array
    //Function to find the sum of contiguous subarray with maximum sum.
    long maxSubarraySum(int arr[], int n){
        
        // Your code here
    long curr_sum = arr[0] ; 
    long overall_sum = arr[0] ; 
    
    for (int i = 1; i<n ; i++) {
        if (curr_sum < 0) {
            curr_sum = arr[i] ; 
        }else {
            curr_sum += arr[i] ;
        }
        if(curr_sum > overall_sum){
            overall_sum = curr_sum ;
        }
    }
     return overall_sum ; 
    }
    
}
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.