# Maximum subarray problem

In computer science, the maximum sum subarray problem, also known as the maximum segment sum problem, is the task of finding a contiguous subarray with the largest sum, within a given one-dimensional array A[1...n] of numbers. It can be solved in $O(n)$ time and $O(1)$ space.
Formally, the task is to find indices $i$ and $j$ with $1\leq i\leq j\leq n$, such that the sum
    $\sum _{x=i}^{j}A[x]$
is as large as possible. (Some formulations of the problem also allow the empty subarray to be considered; by convention, the sum of all values of the empty subarray is zero.) Each number in the input array A could be positive, negative, or zero.
For example, for the array of values [−2, 1, −3, 4, −1, 2, 1, −5, 4], the contiguous subarray with the largest sum is [4, −1, 2, 1], with sum 6.
Some properties of this problem are:
* If the array contains all non-negative numbers, then the problem is trivial; a maximum subarray is the entire array.
* If the array contains all non-positive numbers, then a solution is any subarray of size 1 containing the maximal value of the array (or the empty subarray, if it is permitted).
* Several different sub-arrays may have the same maximum sum.
Although this problem can be solved using several different algorithmic techniques, including brute force, divide and conquer, dynamic programming, and reduction to shortest paths, a simple single-pass algorithm known as Kadane's algorithm solves it efficiently.

## History

The maximum subarray problem was proposed by Ulf Grenander in 1977 as a simplified model for maximum likelihood estimation of patterns in digitized images.
Grenander was looking to find a rectangular subarray with maximum sum, in a two-dimensional array of real numbers. A brute-force algorithm for the two-dimensional problem runs in O(n$^6$) time; because this was prohibitively slow, Grenander proposed the one-dimensional problem to gain insight into its structure. Grenander derived an algorithm that solves the one-dimensional problem in O(n$^2$) time using prefix sum, improving the brute force running time of O(n$^3$). When Michael Shamos heard about the problem, he overnight devised an O(n log n) divide-and-conquer algorithm for it. Soon after, Shamos described the one-dimensional problem and its history at a Carnegie Mellon University seminar attended by Jay Kadane, who designed within a minute an O(n)-time algorithm, which is as fast as possible. In 1982, David Gries obtained the same O(n)-time algorithm by applying Dijkstra's "standard strategy"; in 1989, Richard Bird derived it by purely algebraic manipulation of the brute-force algorithm using the Bird–Meertens formalism.
Grenander's two-dimensional generalization can be solved in O(n$^3$) time either by using Kadane's algorithm as a subroutine, or through a divide-and-conquer approach. Slightly faster algorithms based on distance matrix multiplication have been proposed by Tamaki & Tokuyama (1998) and by Takaoka (2002). There is some evidence that no significantly faster algorithm exists; an algorithm that solves the two-dimensional maximum subarray problem in O(n$^{3−ε}$) time, for any ε>0, would imply a similarly fast algorithm for the all-pairs shortest paths problem.

## Applications

Maximum subarray problems arise in many fields, such as genomic sequence analysis and computer vision.
Genomic sequence analysis employs maximum subarray algorithms to identify important biological segments of protein sequences that have unusual properties, by assigning scores to points within the sequence that are positive when a motif to be recognized is present, and negative when it is not, and then seeking the maximum subarray among these scores. These problems include conserved segments, GC-rich regions, tandem repeats, low-complexity filter, DNA binding domains, and regions of high charge.
In computer vision, bitmap images generally consist only of positive values, for which the maximum subarray problem is trivial: the result is always the whole array. However, after subtracting a threshold value (such as the average pixel value) from each pixel, so that above-average pixels will be positive and below-average pixels will be negative, the maximum subarray problem can be applied to the modified image to detect bright areas within it.

## Kadane's algorithm
### No empty subarrays admitted

Kadane's algorithm scans the given array $A[1\ldots n]$ from left to right. In the $j$th step, it computes the subarray with the largest sum ending at $j$; this sum is maintained in variable current_sum. Moreover, it computes the subarray with the largest sum anywhere in $A[1\ldots j]$, maintained in variable best_sum, and easily obtained as the maximum of all values of current_sum seen so far, cf. line 7 of the algorithm.
As a loop invariant, in the $j$th step, the old value of current_sum holds the maximum over all $i\in \{1,\ldots ,j-1\}$ of the sum $A[i]+\cdots +A[j-1]$. Therefore, current_sum$+A[j]$ is the maximum over all $i\in \{1,\ldots ,j-1\}$ of the sum $A[i]+\cdots +A[j]$. To extend the latter maximum to cover also the case $i=j$, it is sufficient to consider also the singleton subarray $A[j\;\ldots \;j]$. This is done in line 6 by assigning $\max(A[j],$current_sum$+A[j])$ as the new value of current_sum, which after that holds the maximum over all $i\in \{1,\ldots ,j\}$ of the sum $A[i]+\cdots +A[j]$.
Thus, the problem can be solved with the following code, expressed in Python.
If the input contains no positive element, the returned value is that of the largest element (i.e., the value closest to 0), or negative infinity if the input was empty. For correctness, an exception should be raised when the input array is empty, since an empty array has no maximum nonempty subarray. If the array is nonempty, its first element could be used in place of negative infinity, if needed to avoid mixing numeric and non-numeric values.
The algorithm can be adapted to the case which allows empty subarrays or to keep track of the starting and ending indices of the maximum subarray.
This algorithm calculates the maximum subarray ending at each position from the maximum subarray ending at the previous position, so it can be viewed as a case of dynamic programming.

### Empty subarrays admitted

* Example run
* Execution of Kadane's algorithm on the above example array. Blue: subarray with largest sum ending at i; green: subarray with largest sum encountered so far; a lower case letter indicates an empty array; variable i is left implicit in Python code.
Kadane's algorithm, as originally published, is for solving the problem variant which allows empty subarrays. In such variant, the answer is 0 when the input contains no positive elements (including when the input is empty). The variant is obtained with two changes in code: in line 3, best_sum should be initialized to 0 to account for the empty subarray $A[0\ldots -1]$
and line 6 in the for loop current_sum should be updated to max(0, current_sum + x).
As a loop invariant, in the $j$th step, the old value of current_sum holds the maximum over all $i\in \{1,\ldots ,j\}$ of the sum $A[i]+\cdots +A[j-1]$. Therefore, current_sum$+A[j]$ is the maximum over all $i\in \{1,\ldots ,j\}$ of the sum $A[i]+\cdots +A[j]$. To extend the latter maximum to cover also the case $i=j+1$, it is sufficient to consider also the empty subarray $A[j+1\;\ldots \;j]$. This is done in line 6 by assigning $\max(0,$current_sum$+A[j])$ as the new value of current_sum, which after that holds the maximum over all $i\in \{1,\ldots ,j+1\}$ of the sum $A[i]+\cdots +A[j]$. Machine-verified C / Frama-C code of both variants can be found here.

### Computing the best subarray's position

The algorithm can be modified to keep track of the starting and ending indices of the maximum subarray as well.
Because of the way this algorithm uses optimal substructures (the maximum subarray ending at each position is calculated in a simple way from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position) this algorithm can be viewed as a simple/trivial example of dynamic programming.

### Complexity

The runtime complexity of Kadane's algorithm is $O(n)$ and its space complexity is $O(1)$.

## Generalizations

Similar problems may be posed for higher-dimensional arrays, but their solutions are more complicated; see, e.g., Takaoka (2002). Brodal & Jørgensen (2007) showed how to find the k largest subarray sums in a one-dimensional array, in the optimal time bound $O(n+k)$.
The Maximum sum k-disjoint subarrays can also be computed in the optimal time bound $O(n+k)$ .