(Translated by https://www.hiragana.jp/)
Maximum Subarray Sum - Kadane's Algorithm - GeeksforGeeks
Open In App

Maximum Subarray Sum - Kadane's Algorithm

Last Updated : 22 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr[], find the subarray (containing at least one element) which has the maximum possible sum, and return that sum.
Note: A subarray is a continuous part of an array.

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 Java Python C# JavaScript

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.

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:

C++
C Java Python C# JavaScript

Output
11

Related Articles:


Maximum Subarray Sum
Visit Course explore course icon
Video Thumbnail

Maximum Subarray Sum

Video Thumbnail

Maximum Sum Subarray

Similar Reads