Given an integer array, find a contiguous subarray within it that has the largest sum.

For example,

Input:  {-2, 1, -3, 4, -1, 2, 1, -5, 4}
 
Output: Subarray with the largest sum is {4, -1, 2, 1} with sum 6.

Practice this problem

The problem differs from the problem of finding the maximum sum subsequence. Unlike subsequences, subarrays are required to occupy consecutive positions within the original array.

 
We can easily solve this problem in linear time using Kadane’s algorithm. The idea is to maintain a maximum (positive-sum) subarray “ending” at each index of the given array. This subarray is either empty (in which case its sum is zero) or consists of one more element than the maximum subarray ending at the previous index.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum sum of a contiguous subarray is 6

Java


Download  Run Code

Output:

The maximum sum of a contiguous subarray is 6

Python


Download  Run Code

Output:

The maximum sum of a contiguous subarray is 6

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.
 

 
The above code doesn’t handle the case when all the array elements are negative. If the array contains all negative values, the answer is the maximum element. We can easily place this check before continuing to the algorithm. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum sum of a contiguous subarray is -2

Java


Download  Run Code

Output:

The maximum sum of a contiguous subarray is -2

Python


Download  Run Code

Output:

The maximum sum of a contiguous subarray is -2

This approach requires two traversals of the input array. We can easily modify the main algorithm to handle negative integers as well. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum sum of a contiguous subarray is -2

Java


Download  Run Code

Output:

The maximum sum of a contiguous subarray is -2

Python


Download  Run Code

Output:

The maximum sum of a contiguous subarray is -2

Because of the way this algorithm uses optimal substructures (the maximum subarray ending at each position is calculated merely from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position), this algorithm can be viewed as a simple example of dynamic programming.

 
Related Post:

Print continuous subarray with maximum sum

 
References: https://en.wikipedia.org/wiki/Maximum_subarray_problem