Given an integer array, find and print a contiguous subarray with the maximum sum in it.

For example,

Input:  {-2, 1, -3, 4, -1, 2, 1, -5, 4}
 
Output: The contiguous subarray with the largest sum is {4, -1, 2, 1}
 
 
Input:  {8, -7, -3, 5, 6, -2, 3, -4, 2}
 
Output: The contiguous subarray with the largest sum is {5, 6, -2, 3}

Practice this problem

We can easily solve this problem in linear time by maintaining the maximum subarray sum ending at each array index. Then,

  • The subarray is either empty in which case its sum is zero, or
  • It consists of one more element than the maximum subarray ending at the previous index.

We have already discussed this approach using Kadane’s algorithm, but that only output the sum of contiguous subarray having the largest sum but do not print the subarray itself. We can easily modify the algorithm to keep track of the maximum subarray’s starting and ending indices. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The contiguous subarray with the largest sum is 4 -1 2 1

Java


Download  Run Code

Output:

The contiguous subarray with the largest sum is [4, -1, 2, 1]

Python


Download  Run Code

Output:

The contiguous sublist with the largest sum is [4, -1, 2, 1]

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the input.