Maximum Subarray Problem
   HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, 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 An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
A ...nof numbers. Formally, the task is to find indices i and j with 1 \leq i \leq j \leq n , such that the sum : \sum_^j A 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 minus;2, 1, −3, 4, −1, 2, 1, −5, 4 the contiguous subarray with the largest sum is , −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. This problem can be solved using several different algorithmic techniques, including brute force, divide and conquer, dynamic programming, and reduction to shortest paths.


History

The maximum subarray problem was proposed by
Ulf Grenander Ulf Grenander (23 July 1923 – 12 May 2016) was a Swedish statistician and professor of applied mathematics at Brown University. His early research was in probability theory, stochastic processes, time series analysis, and statistical theory (pa ...
in 1977 as a simplified model for
maximum likelihood estimation In statistics, maximum likelihood estimation (MLE) is a method of estimating the parameters of an assumed probability distribution, given some observed data. This is achieved by maximizing a likelihood function so that, under the assumed statis ...
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, 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 In computer science, divide and conquer is an algorithm design paradigm. A divide-and-conquer algorithm recursively breaks down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved dire ...
for it. Soon after, Shamos described the one-dimensional problem and its history at a
Carnegie Mellon University Carnegie Mellon University (CMU) is a private research university in Pittsburgh, Pennsylvania. One of its predecessors was established in 1900 by Andrew Carnegie as the Carnegie Technical Schools; it became the Carnegie Institute of Technology ...
seminar attended by Jay Kadane, who designed within a minute an ''O''(''n'')-time algorithm, which is as fast as possible.since every algorithm must at least scan the array once which already takes ''O''(''n'') time In 1982,
David Gries David Gries (born April 26, 1939 in Flushing, Queens, New York) is an American computer scientist at Cornell University, United States mainly known for his books ''The Science of Programming'' (1981) and ''A Logical Approach to Discrete Math'' ( ...
obtained the same ''O''(''n'')-time algorithm by applying
Dijkstra Dijkstra ( or ) is a Dutch family name of West Frisian origin. It most commonly refers to: * Edsger W. Dijkstra (1930–2002), Dutch computer scientist ** Named after him: Dijkstra's algorithm, Dijkstra Prize, Dijkstra–Scholten algorithm Dijks ...
's "standard strategy"; in 1989, Richard Bird derived it by purely algebraic manipulation of the brute-force algorithm using the
Bird–Meertens formalism The Bird–Meertens formalism (BMF) is a calculus for deriving programs from specifications (in a functional-programming setting) by a process of equational reasoning. It was devised by Richard Bird and Lambert Meertens as part of their work with ...
. 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 and by . 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 In bioinformatics, sequence analysis is the process of subjecting a DNA, RNA or peptide sequence to any of a wide range of analytical methods to understand its features, function, structure, or evolution. Methodologies used include sequence alignm ...
and
computer vision Computer vision is an interdisciplinary scientific field that deals with how computers can gain high-level understanding from digital images or videos. From the perspective of engineering, it seeks to understand and automate tasks that the hum ...
. Genomic sequence analysis employs maximum subarray algorithms to identify important biological segments of protein sequences. These problems include conserved segments, GC-rich regions, tandem repeats, low-complexity filter, DNA binding domains, and regions of high charge. In
computer vision Computer vision is an interdisciplinary scientific field that deals with how computers can gain high-level understanding from digital images or videos. From the perspective of engineering, it seeks to understand and automate tasks that the hum ...
, maximum-subarray algorithms are used on bitmap images to detect the brightest area in an image.


Kadane's algorithm


Empty subarrays admitted

Kadane's original algorithm solves the problem version when empty subarrays are admitted. It scans the given array A \ldots n/math> from left to right. In the jth 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 \ldots j/math>, 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 computer science, a loop invariant is a property of a program loop that is true before (and after) each iteration. It is a logical assertion, sometimes checked within the code by an assertion call. Knowing its invariant(s) is essential in und ...
, in the jth step, the old value of current_sum holds the maximum over all i \in \ of the sum A \cdots+A -1/math>. Therefore, current_sum+A /math> is the maximum over all i \in \ of the sum A \cdots+A /math>. To extend the latter maximum to cover also the case i=j+1, it is sufficient to consider also the empty subarray A +1 \; \ldots \; j/math>. This is done in line 6 by assigning \max(0,current_sum+A as the new value of current_sum, which after that holds the maximum over all i \in \ of the sum A \cdots+A /math>. Thus, the problem can be solved with the following code, expressed here in
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
: def max_subarray(numbers): """Find the largest sum of any contiguous subarray.""" best_sum = 0 current_sum = 0 for x in numbers: current_sum = max(0, current_sum + x) best_sum = max(best_sum, current_sum) return best_sum This version of the algorithm will return 0 if the input contains no positive elements (including when the input is empty).


No empty subarrays admitted

For the variant of the problem which disallows empty subarrays, best_sum should be initialized to negative infinity instead and also in the for loop current_sum should be updated as max(x, current_sum + x). In that case, 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 subarray: def max_subarray(numbers): """Find the largest sum of any contiguous subarray.""" if numbers

[]: raise ValueError('Empty array has no nonempty subarrays') best_sum = float('-inf') current_sum = 0 for x in numbers: current_sum = max(x, current_sum + x) best_sum = max(best_sum, current_sum) return best_sum


Conditionally admitting empty subarrays

The only case when it matters if empty subarrays are admitted, is if all numbers in the input array are negative. In this case, the maximum subarray will either be empty (when empty subarrays are allowed), or contain the largest number in the input array (when empty subarrays are not allowed). An alternative algorithm that admits empty subarrays is easily developed from the algorithm given above which does not admit empty subarrays: The only change that is needed is to return max(best_sum, 0) instead of best_sum. It can be seen that this version is correct: * For an empty input array the previous algorithm will return minus infinity, so this algorithm will return zero, which corresponds to the sum of elements of an empty subarray. * For an input array with only negative numbers, the previous algorithm will return the largest of the integers, which is negative. So this algorithm will return zero, which corresponds to the sum of elements of an empty subarray. * For all other cases, there is at least one nonnegative integer in the output, so there is a nonempty subarray for which the sum of the elements is at least 0. Since the sum of the elements is always zero for empty subarrays, it doesn't matter if empty subarrays are admitted or not, so this algorithm correctly returns the same answer as the previous algorithm gives. This algorithm can also be converted to a version that conditionally admits empty subarrays, based on a parameter: If empty subarrays are admitted, return max(0, best_sum), otherwise, return best_sum. An exception should be raised the input array is empty but empty subarrays are not admitted: def max_subarray(numbers, admit_empty_subarrays=True): """Find the largest sum of any contiguous subarray.""" if not(admit_empty_subarrays) and numbers

[]: raise ValueError('Empty array has no nonempty subarrays') best_sum = float('-inf') current_sum = 0 for x in numbers: current_sum = max(x, current_sum + x) best_sum = max(best_sum, current_sum) if admit_empty_subarrays: best_sum = max(0, best_sum) return best_sum


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: def max_subarray(numbers): """Find a contiguous subarray with the largest sum.""" best_sum = 0 # or: float('-inf') best_start = best_end = 0 # or: None current_sum = 0 for current_end, x in enumerate(numbers): if current_sum <= 0: # Start a new sequence at the current element current_start = current_end current_sum = x else: # Extend the existing sequence with the current element current_sum += x if current_sum > best_sum: best_sum = current_sum best_start = current_start best_end = current_end + 1 # the +1 is to make 'best_end' match Python's slice convention (endpoint excluded) return best_sum, best_start, best_end In Python, arrays are indexed starting from 0, and slices exclude the endpoint, so that the subarray 2, 33in the array a= 11, 22, 33, -44would be expressed as a :3


Complexity

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 Dynamic programming is both a mathematical optimization method and a computer programming method. The method was developed by Richard Bellman in the 1950s and has found applications in numerous fields, from aerospace engineering to economics. I ...
. The runtime complexity of Kadane's algorithm is O(n).


Generalizations

Similar problems may be posed for higher-dimensional arrays, but their solutions are more complicated; see, e.g., . 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) .


See also

*
Subset sum problem The subset sum problem (SSP) is a decision problem in computer science. In its most general formulation, there is a multiset S of integers and a target-sum T, and the question is to decide whether any subset of the integers sum to precisely T''.'' T ...


Notes


References

* *. * * * * *. * *. *


External links

* * * {{Cite web, url=http://cs.slu.edu/~goldwamh/courses/slu/csci314/2012_Fall/lectures/maxsubarray/, title=Notes on Maximum Subarray Problem, date=2012
www.algorithmist.com

alexeigor.wikidot.com

greatest subsequential sum problem on Rosetta Code

geeksforgeeks page on Kadane's Algorithm
Optimization algorithms and methods Dynamic programming Articles with example Python (programming language) code