The Wayback Machine - https://web.archive.org/web/20241126205706/https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
Open In App

Maximum Subarray Sum – Kadane’s Algorithm

Last Updated : 11 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum.

Examples:

Input: arr[] = {2, 3, -8, 7, -1, 2, 3}
Output: 11
Explanation: The subarray {7, -1, 2, 3} has the largest sum 11.

Input: arr[] = {-2, -4}
Output: –2
Explanation: The subarray {-2} has the largest sum -2.

Input: arr[] = {5, 4, 1, 7, 8}
Output: 25
Explanation: The subarray {5, 4, 1, 7, 8} has the largest sum 25.

[Naive Approach] By iterating over all subarrays – O(n^2) Time and O(1) Space

The idea is to run two nested loops to iterate over all possible subarrays and find the maximum sum. The outer loop will mark the starting point of a subarray and inner loop will mark the ending point of the subarray.

C++
// C++ Program to find the maximum subarray sum using nested loops 

#include <bits/stdc++.h>
using namespace std;

// Function to find the sum of subarray with maximum sum
int maxSubarraySum(vector<int> &arr) {
    int res = arr[0];
  
    // Outer loop for starting point of subarray
      for(int i = 0; i < arr.size(); i++) {
        int currSum = 0;
      
        // Inner loop for ending point of subarray
        for(int j = i; j < arr.size(); j++) {
            currSum = currSum + arr[j];
          
            // Update res if currSum is greater than res
            res = max(res, currSum);
        }
    }
    return res;
}

int main() {
    vector<int> arr = {2, 3, -8, 7, -1, 2, 3};
    cout << maxSubarraySum(arr);
    return 0;
}
C
// C Program to find the maximum subarray sum using nested loops

#include <stdio.h>

// Function to find the sum of subarray with maximum sum
int maxSubarraySum(int arr[], int size) {
    int maxSum = arr[0];
  
    // Outer loop for starting point of subarray
    for (int i = 0; i < size; i++) {
        int currSum = 0;
      
        // Inner loop for ending point of subarray
        for (int j = i; j < size; j++) {
            currSum = currSum + arr[j];
          
            // Update maxSum if currSum is greater than maxSum
            if (currSum > maxSum) {
                maxSum = currSum;
            }
        }
    }
    return maxSum;
}

int main() {
    int arr[] = {2, 3, -8, 7, -1, 2, 3};
    int size = sizeof(arr) / sizeof(arr[0]);
    printf("%d", maxSubarraySum(arr, size));
    return 0;
}
Java
// Java Program to find the maximum subarray sum using nested loops 

import java.util.Arrays;

class GfG {

    // Function to find the sum of subarray with maximum sum
    static int maxSubarraySum(int[] arr) {
        int res = arr[0];
  
        // Outer loop for starting point of subarray
        for (int i = 0; i < arr.length; i++) {
            int currSum = 0;
      
            // Inner loop for ending point of subarray
            for (int j = i; j < arr.length; j++) {
                currSum = currSum + arr[j];
              
                // Update res if currSum is greater than res
                res = Math.max(res, currSum);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, -8, 7, -1, 2, 3};
        System.out.println(maxSubarraySum(arr));
    }
}
Python
# Python Program to find the maximum subarray sum using nested loops

# Function to find the sum of subarray with maximum sum
def maxSubarraySum(arr):
    res = arr[0]
  
    # Outer loop for starting point of subarray
    for i in range(len(arr)):
        currSum = 0
      
        # Inner loop for ending point of subarray
        for j in range(i, len(arr)):
            currSum = currSum + arr[j]
          
            # Update res if currSum is greater than res
            res = max(res, currSum)
          
    return res

if __name__ == "__main__":
    arr = [2, 3, -8, 7, -1, 2, 3]
    print(maxSubarraySum(arr))
C#
// C# Program to find the maximum subarray sum using nested loops

using System;

class GfG {
    
    // Function to find the sum of subarray with maximum sum
    static int MaxSubarraySum(int[] arr) {
        int res = arr[0];
  
        // Outer loop for starting point of subarray
        for (int i = 0; i < arr.Length; i++) {
            int currSum = 0;
      
            // Inner loop for ending point of subarray
            for (int j = i; j < arr.Length; j++) {
                currSum = currSum + arr[j];
              
                // Update res if currSum is greater than res
                res = Math.Max(res, currSum);
            }
        }
        return res;
    }

    static void Main() {
        int[] arr = {2, 3, -8, 7, -1, 2, 3};
        Console.WriteLine(MaxSubarraySum(arr));
    }
}
JavaScript
// JavaScript Program to find the maximum subarray sum using nested loops 

// Function to find the sum of subarray with maximum sum
function maxSubarraySum(arr) {
    let res = arr[0];
  
    // Outer loop for starting point of subarray
    for (let i = 0; i < arr.length; i++) {
        let currSum = 0;
      
        // Inner loop for ending point of subarray
        for (let j = i; j < arr.length; j++) {
            currSum = currSum + arr[j];
          
            // Update res if currSum is greater than res
            res = Math.max(res, currSum);
        }
    }
    return res;
}

const arr = [2, 3, -8, 7, -1, 2, 3];
console.log(maxSubarraySum(arr));

Output
11

[Expected Approach] Using Kadane’s Algorithm – O(n) Time and O(1) Space

The idea of Kadane’s algorithm is to traverse over the array from left to right and for each element, find the maximum sum among all subarrays ending at that element. The result will be the maximum of all these values.

But, the main issue is how to calculate maximum sum among all the subarrays ending at an element in O(1) time?

To calculate the maximum sum of subarray ending at current element, say maxEnding, we can use the maximum sum ending at the previous element. So for any element, we have two choices:

  • Choice 1: Extend the maximum sum subarray ending at the previous element by adding the current element to it. If the maximum subarray sum ending at the previous index is positive, then it is always better to extend the subarray.
  • Choice 2: Start a new subarray starting from the current element. If the maximum subarray sum ending at the previous index is negative, it is always better to start a new subarray from the current element.

This means that maxEnding at index i = max(maxEnding at index (i – 1) + arr[i], arr[i]) and the maximum value of maxEnding at any index will be our answer.

Illustration:


Below is the implementation of the above algorithm:

C++
// C++ Program for Maximum Subarray Sum using Kadane's Algorithm

#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum subarray sum
int maxSubarraySum(vector<int> &arr) {
    int res = arr[0];
    int maxEnding = arr[0];

    for (int i = 1; i < arr.size(); i++) {
      
        // Find the maximum sum ending at index i by either extending 
        // the maximum sum subarray ending at index i - 1 or by
        // starting a new subarray from index i
        maxEnding = max(maxEnding + arr[i], arr[i]);
      
        // Update res if maximum subarray sum ending at index i > res
        res = max(res, maxEnding);
    }
    return res;
}

int main() {
    vector<int> arr = {2, 3, -8, 7, -1, 2, 3};
    cout << maxSubarraySum(arr);
    return 0;
}
C
// C Program for Maximum Subarray Sum using Kadane's Algorithm

#include <stdio.h>
#include <limits.h>

// Function to find the maximum subarray sum
int maxSubarraySum(int arr[], int size) {
    int res = arr[0];
    int maxEnding = arr[0];

    for (int i = 1; i < size; i++) {
        
        // Find the maximum sum ending at index i by either extending 
        // the maximum sum subarray ending at index i - 1 or by
        // starting a new subarray from index i
        maxEnding = (maxEnding + arr[i] > arr[i]) ? 
                                              maxEnding + arr[i] : arr[i];
      
        // Update res if maximum subarray sum ending at index i > res
        res = (res > maxEnding) ? res : maxEnding;
    }
    return res;
}

int main() {
    int arr[] = {2, 3, -8, 7, -1, 2, 3};
    int size = sizeof(arr) / sizeof(arr[0]);
    printf("%lld\n", maxSubarraySum(arr, size));
    return 0;
}
Java
// Java Program for Maximum Subarray Sum using Kadane's Algorithm

import java.util.Arrays;

class GfG {

    // Function to find the maximum subarray sum
    static int maxSubarraySum(int[] arr) {
        int res = arr[0];
        int maxEnding = arr[0];

        for (int i = 1; i < arr.length; i++) {
            
            // Find the maximum sum ending at index i by either extending 
            // the maximum sum subarray ending at index i - 1 or by
            // starting a new subarray from index i
            maxEnding = Math.max(maxEnding + arr[i], arr[i]);
          
            // Update res if maximum subarray sum ending at index i > res
            res = Math.max(res, maxEnding);
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, -8, 7, -1, 2, 3};
        System.out.println(maxSubarraySum(arr));
    }
}
Python
# Python Program for Maximum Subarray Sum using Kadane's Algorithm

# Function to find the maximum subarray sum
def maxSubarraySum(arr):
    
    res = arr[0]
    maxEnding = arr[0]

    for i in range(1, len(arr)):
        
        # Find the maximum sum ending at index i by either extending 
        # the maximum sum subarray ending at index i - 1 or by
        # starting a new subarray from index i
        maxEnding = max(maxEnding + arr[i], arr[i])
        
        # Update res if maximum subarray sum ending at index i > res
        res = max(res, maxEnding)
    
    return res

arr = [2, 3, -8, 7, -1, 2, 3]
print(maxSubarraySum(arr))
C#
// C# Program for Maximum Subarray Sum using Kadane's Algorithm

using System;

class GfG {
    
    // Function to find the maximum subarray sum
    static int MaxSubarraySum(int[] arr) {
        int res = arr[0];
        int maxEnding = arr[0];

        for (int i = 1; i < arr.Length; i++) {
            
            // Find the maximum sum ending at index i by either extending 
            // the maximum sum subarray ending at index i - 1 or by
            // starting a new subarray from index i
            maxEnding = Math.Max(maxEnding + arr[i], arr[i]);
            
            // Update res if maximum subarray sum ending at index i > res
            res = Math.Max(res, maxEnding);
        }
        return res;
    }

    static void Main() {
        int[] arr = { 2, 3, -8, 7, -1, 2, 3 };
        Console.WriteLine(MaxSubarraySum(arr));
    }
}
JavaScript
// JavaScript Program for Maximum Subarray Sum using Kadane's Algorithm

// Function to find the maximum subarray sum
function maxSubarraySum(arr) {
    let res = arr[0];
    let maxEnding = arr[0];

    for (let i = 1; i < arr.length; i++) {
        
        // Find the maximum sum ending at index i by either extending 
        // the maximum sum subarray ending at index i - 1 or by
        // starting a new subarray from index i
        maxEnding = Math.max(maxEnding + arr[i], arr[i]);
        
        // Update res if maximum subarray sum ending at index i > res
        res = Math.max(res, maxEnding);
    }
    return res;
}

const arr = [2, 3, -8, 7, -1, 2, 3];
console.log(maxSubarraySum(arr));

Output
11

Time Complexity: O(n), since we are traversing the array only one time.
Auxiliary Space: O(1)

Related Articles:



Previous Article
Next Article

Similar Reads

3D Kadane's Algorithm
What is Kadane's Algorithm?Kadane's algorithm is a dynamic programming technique used to find the maximum subarray sum within a one-dimensional array. It efficiently computes the maximum sum of a contiguous subarray, and its simplicity and effectiveness make it a popular choice for solving related problems. Idea/Working of Kadane's Algorithm:The id
14 min read
First subarray having sum at least half the maximum sum of any subarray of size K
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum possible sum from any subarray of size K is 16 fr
9 min read
Maximum Subarray Sum using Divide and Conquer algorithm
You are given a one dimensional array that may contain both positive and negative integers, find the sum of contiguous subarray of numbers which has the largest sum. For example, if the given array is {-2, -5, 6, -2, -3, 1, 5, -6}, then the maximum subarray sum is 7 (see highlighted elements). Recommended: Please solve it on “PRACTICE ” first, befo
12 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 min read
Maximum sum subarray having sum less than or equal to given sum
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. Note: Given array contains only non-negative integers. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } sum = 11Output: 10Subarray having maximum sum is { 1, 2, 3, 4 }Input: arr[] = { 2, 4, 6, 8, 10
10 min read
Maximum length of subarray such that all elements are equal in the subarray
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2, 3, 4} Output: 1 Explanation: All identical elemen
5 min read
Maximum sum of K-length subarray with maximum count of distinct prime factors
Given an array arr[] consisting of N positive integers and an integer K, the task is to find the maximum sum of array elements in a subarray having maximum sum of distinct prime factors in each K-length subarray. Note: If there are multiple answers then print the sum of the original subarray having maximum sum. Examples: Input: arr[] = {1, 4, 2, 10
11 min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost
Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation with the cost equal to the sum of elements of the su
11 min read
Maximize the subarray sum after multiplying all elements of any subarray with X
Given an array arr[] of N integers and an integer X. We can choose any sub-array and multiply all its element by X. After multiplication, find the sub-array with the maximum sum. The task is to multiply the sub-array in such a way that the final sub-array sum is maximized. Examples: Input: arr[] = { -3, 8, -2, 1, -6 }, X = -1 Output: 15 Choose the
15+ min read
Find minimum subarray sum for each index i in subarray [i, N-1]
Given an array arr[] of size N, the task is to find the minimum subarray sum in the subarrays [i, N-1] for all i in [0, N-1]. Examples: Input: arr[ ] = {3, -1, -2}Output: -3 -3 -2Explanation: For (i = 1) i.e. {3, -1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 2) i.e. {-1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 3) i
9 min read
Maximize subarray sum by inverting sign of elements of any subarray at most twice
Given an array A of size n, find the maximum subarray sum after applying the given operation at most two times. In one operation, choose any two indices i and j and invert sign of all the elements from index i to index j, i.e, all positive elements in the range i to j become negative and all negative elements become positive. Examples: Input: A[] =
10 min read
Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Count of subarray that does not contain any subarray with sum 0
Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements may not be distinct.Examples: Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not contain any subarray whose elements sum is equal to
11 min read
Maximum subarray sum in O(n) using prefix sum
Given an Array of Positive and Negative Integers, find out the Maximum Subarray Sum in that Array. Examples: Input1 : arr = {-2, -3, 4, -1, -2, 1, 5, -3} Output1 : 7 Input2 : arr = {4, -8, 9, -4, 1, -8, -1, 6} Output2 : 9 Kadane's Algorithm solves this problem using Dynamic Programming approach in linear time. Here is another approach using Dynamic
8 min read
Maximum sum subarray of size K with sum less than X
Given an array arr[] and two integers K and X, the task is to find the maximum sum among all subarrays of size K with the sum less than X. Examples: Input: arr[] = {20, 2, 3, 10, 5}, K = 3, X = 20Output: 18Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, required output is 18. Input: arr[] = {-5, 8, 7, 2, 10
7 min read
Smallest pair of indices with product of subarray co-prime with product of the subarray on the left or right
Given an array arr[] of length N, the task is to find the smallest pair of indices (i, j) such that the product of elements in the subarray arr[i + 1, j - 1] is co-prime with either the product of the subarray arr[0, i] or that of the subarray arr[j, N]. If no such pair exists, the print "-1". Examples: Input: arr[] = {2, 4, 1, 3, 7}Output: (0, 2)E
12 min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Maximum Subarray Sum in a given Range
Given an array of n numbers, the task is to answer the following queries: maximumSubarraySum(start, end) : Find the maximum subarray sum in the range from array index 'start' to 'end'. Also see : Range Query With Update Required Examples: Input : arr[] = {1, 3, -4, 5, -2} Query 1: start = 0, end = 4 Query 2: start = 0, end = 2 Output : 5 4 Explanat
15+ min read
Size of The Subarray With Maximum Sum
Given an array arr[] of size N, the task is to find the length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1} Output : Length of the subarray is 2 Explanation : Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2 Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 } Output : Length of the su
10 min read
Maximum Subarray Sum Excluding Certain Elements
Given an array of A of n integers and an array B of m integers find the Maximum Contiguous Subarray Sum of array A such that any element of array B is not present in that subarray. Examples : Input : A = {1, 7, -10, 6, 2}, B = {5, 6, 7, 1} Output : 2 Explanation Since the Maximum Sum Subarray of A is not allowed to have any element that is present
15+ min read
Split array to three subarrays such that sum of first and third subarray is equal and maximum
Given an array of N integers, the task is to print the sum of the first subarray by splitting the array into exactly three subarrays such that the sum of the first and third subarray elements are equal and the maximum. Note: All the elements must belong to a subarray and the subarrays can also be empty. Examples: Input: a[] = {1, 3, 1, 1, 4} Output
13 min read
Maximum sum subarray such that start and end values are same
Given an array of N positive numbers, the task is to find a contiguous subarray (L-R) such that a[L]=a[R] and sum of a[L] + a[L+1] +...+ a[R] is maximum. Examples: Input: arr[] = {1, 3, 2, 2, 3} Output: 10 Subarray [3, 2, 2, 3] starts and ends with 3 and has sum = 10 Input: arr[] = {1, 3, 2, 2, 3} Output: 10 Approach: For every element in the array
6 min read
Maximum subarray sum in array formed by repeating the given array k times
Given an integer k and an integer array arr[] of n elements, the task is to find the largest sub-array sum in the modified array (formed by repeating the given array k times). For example, if arr[] = {1, 2} and k = 3 then the modified array will be {1, 2, 1, 2, 1, 2}. Examples: Input: arr[] = {1, 2}, k = 3 Output: 9 Modified array will be {1, 2, 1,
12 min read
Maximum subarray sum by flipping signs of at most K array elements
Given an array arr[] of N integers and an integer K, The task is to find the maximum sub-array sum by flipping signs of at most K array elements. Examples: Input: arr[] = {-6, 2, -1, -1000, 2}, k = 2 Output: 1009 We can flip the signs of -6 and -1000, to get maximum subarray sum as 1009 Input: arr[] = {-1, -2, -100, -10}, k = 1 Output: 100 We can o
9 min read
Maximum Subarray Sum after inverting at most two elements
Given an array arr[] of integer elements, the task is to find maximum possible sub-array sum after changing the signs of at most two elements.Examples: Input: arr[] = {-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6} Output: 61 We can get 61 from index 0 to 10 by changing the sign of elements at 4th and 7th indices i.e. -8 and -9. We could have chosen -5 and
11 min read
Maximize product of subarray sum with its maximum element
Given an array arr[] consisting of N positive integers, the task is to find the maximum product of the subarray sum with the maximum element of that subarray. Examples: Input: arr[] = {2, -3, 8, -2, 5}Output: 88Explanation:The required maximum product can be obtained using subarray {8, -2, 5}Therefore, maximum product = (8 + (-2) + 5) * (8) = 88. I
8 min read
Maximum circular subarray sum of size K
Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also). Examples: Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3 Output: max circular sum = 32 start index = 9 end index = 1 Explanation: Maximum Sum = 10 + 18 + 4 = 32 Input: arr =
6 min read
Maximum sum subarray after altering the array
Given an array arr[] of size N. The task is to find the maximum subarray sum possible after performing the given operation at most once. In a single operation, you can choose any index i and either the subarray arr[0...i] or the subarray arr[i...N-1] can be reversed. Examples: Input: arr[] = {3, 4, -2, 1, 3} Output: 11 After reversing arr[0...2], a
15+ min read
Minimum size Subarray with maximum sum in non-increasing order
Given an array arr, the task is to find a subarray of the array elements whose sum is strictly greater than the rest of the elements. The size of the subarray should be minimum and the sum should be maximum and it must be in non-increasing order.Examples: Input: arr = [7, 6, 13, 12, 11] Output: 13 12 Explanation: The subarray [13, 12] and [13, 11]
6 min read
Subarray with largest sum after excluding its maximum element
Given an array arr[], the task is to find the starting and ending indices of the subarray with the largest sum after excluding its maximum element.Examples: Input: arr[] = {5, -2, 10, -1, 4} Output: 1 5 Explanation: Subarray[1:5] = {5, -2, 10, -1, 4} Sum of subarray excluding maximum element = 5 + (-2) + (-1) + 4 = 6Input: arr[] = {5, 2, 5, 3, -30,
9 min read
three90RightbarBannerImg