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
abhishekips07in 3 hours
Python Approach.
class Solution:
    ##Complete this function
    #Function to find the sum of contiguous subarray with maximum sum.
    def maxSubArraySum(self,arr,N):
        ##Your code here
        curr=0
        maxi=float('-inf')
        for i in arr:
            curr+=i
            maxi=max(curr,maxi)
            if curr<0:
                curr=0
        return maxi

0
sakshianie24104 hours ago
// { Driver Code Startsimport java.io.*;
class Main {   public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases while(t-->0){     //size of array     int n = Integer.parseInt(br.readLine().trim());     int arr[] = new int[n];     String inputLine[] = br.readLine().trim().split(" ");          //adding elements     for(int i=0; i<n; i++){         arr[i] = Integer.parseInt(inputLine[i]);     }          Solution obj = new Solution();          //calling maxSubarraySum() function     System.out.println(obj.maxSubarraySum(arr, n)); }}}
// } Driver Code Ends
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       int maxsum=0;       int currsum=0;       for (int i=0:i<n;i++){           currsum+=arr[i];           if(currsum>maxsum){               maxsum=currsum;           }
          If(currsum<0){                currsum=0;//discard
        }                     }          }   }
 
0
aliakbarqeqk7 hours ago
class Solution{
      long maxSubarraySum(int arr[], int n){                     int flag=0,max=arr[0];      for(int i=0;i<n;i++)       {            if(arr[i]>=0)           {               flag=1;               break;           }           else{               if(max<arr[i])               max=arr[i];           }       }              if(flag==0)       {           long res=max;           return res;       }       else{          long curr=0, far=0;                            for(int i=0;i<n;i++)       {          curr = curr + arr[i];                    if(curr>far)          far=curr;                    if(curr<0)          curr=0;                  }                     return far;       }          }   }
0
aditirai630638 hours ago
long maxSubarraySum(int nums[], int n){       long max = Integer.MIN_VALUE, sum = 0;  for(int i=0;i<n;i++){           sum += nums[i];           max = Math.max(sum,max);        if(sum<0) sum = 0;       }
 return max;
0
madhavagrawal315 hours ago
JAVA Solution :
 long maxSubarraySum(int nums[], int n){
        
      long largestSum = nums[0];
      long currentMax = nums[0];
        
      for(int i=1; i<nums.length; i++){
          
          //Continue with the same SubArray :
          currentMax += nums[i];
          
          //Should I start a new SubArray :
          if(currentMax<nums[i]){
              currentMax = nums[i];
          }
          
          if(largestSum<currentMax){
              largestSum  = currentMax;
          }
      }
        return largestSum; 
        
    }
0
pritamlanke2 days ago
int maxi=INT_MIN;       int sum=0;       for(int i=0;i<n;i++){           sum+=arr[i];           maxi=max(maxi,sum);           if(sum<=0)sum=0;       }       return maxi;
+1
aniketg7212 days ago
Easy Java Solution
class Solution{

    long maxSubarraySum(int arr[], int n){
        long maxSum= Integer.MIN_VALUE;
        long sum=0;
        for(int i=0; i<n; i++){
            sum+= arr[i];
            maxSum= Math.max(maxSum, sum);
            
            if(sum<=0) sum= 0;
        }
        return maxSum;
        
    }
    
}
+1
sanyam goyal2 days ago
Idea is to find middle of the array and than find the left_sum(from 0, mid) and right_sum(from mid+1, n-1) and the sum of elements which are crossing into both left_arr and right_arr.
 
long maxSubarraySum(int arr[], int n){
       return maximumSubArraySum(arr, 0, n-1);
   }
   
   private static Integer maximumSubArraySum(int[] A, int low, int high) {
       if(high == low) {
           return A[low];
       } else {
           int mid = (low + high)/2;
           int leftSum = maximumSubArraySum(A, low, mid);
           int rightSum = maximumSubArraySum(A, mid+1, high);
           int crossSum = maximumCrossingSubArraySum(A,low,mid,high);
   
           if(leftSum >= rightSum && leftSum >=crossSum) {
               return leftSum;
           } else if(rightSum >= leftSum && rightSum >= crossSum) {
               return rightSum;
           } else {
               return crossSum;
           }
       }
   }
   
   private static Integer maximumCrossingSubArraySum(int[] A, int low, int mid, int high) {
       int leftSumSub = Integer.MIN_VALUE;
       int sum = 0;
       for(int i=mid;i>=low;i--) {
           sum = sum + A[i];
           if(sum > leftSumSub) {
               leftSumSub = sum;
           }
       }
   
       int rightSumSub = Integer.MIN_VALUE;
       sum = 0;
       for(int i=mid+1;i<=high;i++) {
           sum = sum + A[i];
           if(sum > rightSumSub) {
               rightSumSub = sum;
           }
       }
   
       return leftSumSub + rightSumSub;
   }
 
+1
abhinayabhi1413 days ago
  long maxSubarraySum(int arr[], int n){              // Your code here         long currsum =0;      long maxsum =Long.MIN_VALUE;            for(int i =0; i <n ;i++){// O(n)                    currsum += arr[i];// calculating all the sums           if(currsum >maxsum){ // agr mera sum curr is grater than the max to update the value              maxsum = currsum;          }                    if(currsum < 0){ // at a point my curr is becoming 0 tabh refresh the value of curr to 0              currsum =0;          }             }      return maxsum;   }   }
0
harshdeep57083 days ago
Kadane's Algo.   
    
      long long maxSubarraySum(int arr[], int N){
        long sum=0;
        long maxi=INT_MIN;
        for(int i=0;i<N;i++)
        {
            sum+=arr[i];
            maxi=max(sum,maxi);
            if(sum<0)
            sum=0;
        }
        return maxi;
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.