Maximum subarray problem: Difference between revisions

Content deleted Content added
Empty subarrays admitted: fix misunderstanding: described changes obtain the algorithm variant
 
(606 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|Problem in computer science}}
In [[computer science]], the '''maximum subarray problem''' is the task of finding the contiguous subarray within a one-dimensional [[array]] of numbers (containing at least one positive number) which has the largest sum. For example, for the sequence 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.
[[File:Maximum Subarray Visualization.svg|thumbnail|Visualization of how sub-arrays change based on start and end positions of a sample. Each possible contiguous sub-array is represented by a point on a colored line. That point's y-coordinate represents the sum of the sample. Its x-coordinate represents the end of the sample, and the leftmost point on that colored line represents the start of the sample. In this case, the array from which samples are taken is [2, 3, -1, -20, 5, 10]. ]]
 
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 data structure|array]] A[1...n] of numbers. It can be solved in <math>O(n)</math> time and <math>O(1)</math> space.
The problem was first posed by [[Ulf Grenander]] of [[Brown University]] in 1977, as a simplified model for [[maximum likelihood]] estimation of patterns in digitized images. A [[linear time]] [[algorithm]] was found soon afterwards by [[Jay Kadane]] of [[Carnegie-Mellon University]] ({{harvtxt|Bentley|1984}}).
 
Formally, the task is to find indices <math>i</math> and <math>j</math> with <math>1 \leq i \leq j \leq n </math>, such that the sum
: <math>\sum_{x=i}^j A[x] </math>
is as large as possible. (Some formulations of the problem also allow the empty subarray to be considered; by convention, [[empty sum|the sum of all values of the empty subarray]] is zero.) Each number in the input array A could be positive, negative, or zero.{{sfn|Bentley|1989|p=69}}
 
For example, for the array of values [&minus;2, 1, &minus;3, 4, &minus;1, 2, 1, &minus;5, 4], the contiguous subarray with the largest sum is [4, &minus;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,{{sfn|Bentley|1989|p=70}} divide and conquer,{{sfn|Bentley|1989|p=73}} dynamic programming,{{sfn|Bentley|1989|p=74}} 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.{{sfn|Bentley|1984|p=868-869}}
 
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''<sup>6</sup>) 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''<sup>2</sup>) time using [[prefix sum]]{{NoteTag
|By using a precomputed table of cumulative sums <math>S[k] = \sum_{x=1}^k A[x]</math> to compute the subarray sum <math>\sum_{x=i}^j A[x] = S[j] - S[i-1]</math> in constant time<!--sentence fragment-->
}}, improving the brute force running time of ''O''(''n''<sup>3</sup>). 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,{{sfn|Bentley|1984|p=868-869}}{{sfn|Bentley|1989|p=76-77}}{{sfn|Gries|1982|p=211}} which is as fast as possible.<ref group=note>since every algorithm must at least scan the array once which already takes ''O''(''n'') time</ref> In 1982, [[David Gries]] obtained the same ''O''(''n'')-time algorithm by applying [[Edsger W. Dijkstra |Dijkstra]]'s "standard strategy";{{sfn|Gries|1982|p=209-211}} in 1989, [[Richard Bird (computer scientist)|Richard Bird]] derived it by purely algebraic manipulation of the brute-force algorithm using the [[Bird–Meertens formalism]].{{sfn|Bird|1989|loc=Sect.8, p.126}}
 
Grenander's two-dimensional generalization can be solved in O(''n''<sup>3</sup>) time either by using Kadane's algorithm as a subroutine, or through a divide-and-conquer approach. Slightly faster algorithms based on [[Min-plus matrix multiplication|distance matrix multiplication]] have been proposed by {{harvtxt|Tamaki|Tokuyama|1998}} and by {{harvtxt|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''<sup>3&minus;ε</sup>) time, for any ε>0, would imply a similarly fast algorithm for the [[Shortest path problem#All-pairs shortest paths|all-pairs shortest paths]] problem.{{sfn|Backurs|Dikkala|Tzamos|2016}}
 
== 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.<ref>{{harvtxt|Ruzzo|Tompa|1999}}; {{harvtxt|Alves|Cáceres|Song|2004}}</ref>
 
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.<ref>{{harvtxt|Bae|Takaoka|2006}}; {{harvtxt|Weddell|Read|Thaher|Takaoka|2013}}</ref>
 
==Kadane's algorithm==
===No empty subarrays admitted===
Kadane's algorithm consists of a scan through the array values, computing at each position the maximum subarray ending at that position. This subarray is either empty (in which case [[empty sum|its sum is zero]]) or consists of one more element than the maximum subarray ending at the previous position. Thus, the problem can be solved with the following code, expressed here in [[Python (programming language)|Python]]:
 
[[Joseph Born Kadane|Kadane's]] algorithm scans the given array <math>A[1\ldots n]</math> from left to right.
<source lang="python">
In the <math>j</math>th step, it computes the subarray with the largest sum ending at <math>j</math>; this sum is maintained in variable <code>current_sum</code>.{{NoteTag
def max_subarray(A):
|named <code>MaxEndingHere</code> in {{harvtxt|Bentley|1989}}, and <code>c</code> in {{harvtxt|Gries|1982}}
max_so_far = max_ending_here = 0
}}
for x in A:
Moreover, it computes the subarray with the largest sum anywhere in <math>A[1 \ldots j]</math>, maintained in variable <code>best_sum</code>,{{NoteTag
max_ending_here = max(0, max_ending_here + x)
|named <code>MaxSoFar</code> in {{harvtxt|Bentley|1989}}, and <code>s</code> in {{harvtxt|Gries|1982}}
max_so_far = max(max_so_far, max_ending_here)
}}
return max_so_far
and easily obtained as the maximum of all values of <code>current_sum</code> seen so far, cf. line 7 of the algorithm.
</source>
 
As a [[loop invariant]], in the <math>j</math>th step, the old value of <code>current_sum</code> holds the maximum over all <math>i \in \{ 1,\ldots, j-1 \}</math> of the sum <math>A[i]+\cdots+A[j-1]</math>.
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 example of [[dynamic programming]].
Therefore, <code>current_sum</code><math>+A[j]</math>{{NoteTag|
In the Python code below, <math>A[j]</math> is expressed as <code>x</code>, with the index <math>j</math> left implicit.
}}
is the maximum over all <math>i \in \{ 1,\ldots, j-1 \}</math> of the sum <math>A[i]+\cdots+A[j]</math>. To extend the latter maximum to cover also the case <math>i=j</math>, it is sufficient to consider also the singleton subarray <math>A[j \; \ldots \; j]</math>. This is done in line 6 by assigning <math>\max(A[j],</math><code>current_sum</code><math>+A[j])</math> as the new value of <code>current_sum</code>, which after that holds the maximum over all <math>i \in \{ 1, \ldots, j \}</math> of the sum <math>A[i]+\cdots+A[j]</math>.
 
Thus, the problem can be solved with the following code,{{sfn|Bentley|1989|p=78,171|ps=. Bentley, like Gries, first introduces the variant admitting empty subarrays, see [[#Empty subarrays admitted|below]], and describes only the changes.}} expressed in [[Python (programming language)|Python]].
==Generalizations==
 
Similar problems may be posed for higher dimensional arrays, but their solution is more complicated; see, e.g., {{harvtxt|Takaoka|2002}}. {{harvtxt|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''&nbsp;+&nbsp;''k'').
<syntaxhighlight lang="python" line>
def max_subarray(numbers):
"""Find the largest sum of any contiguous subarray."""
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
</syntaxhighlight>
 
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===
{| align="right" class="wikitable collapsible collapsed"
! Example run
|-
| [[File:Kadane run −2,1,−3,4,−1,2,1,−5,4.gif|thumb|500px|Execution of Kadane's algorithm on the [[#top|above]] example array. ''{{color|#0000c0|Blue}}:'' subarray with largest sum ending at ''i''; ''{{color|#00c000|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.{{sfn|Bentley|1989|p=74}}{{sfn|Gries|1982|p=211}}
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, <code>best_sum</code> should be initialized to 0 to account for the empty subarray <math>A[0 \ldots -1]</math>
<syntaxhighlight lang="python" line start="3">
best_sum = 0;
</syntaxhighlight>
and line 6 in the for loop <code>current_sum</code> should be updated to <code>max(0, current_sum + x)</code>.{{NoteTag
|While {{harvtxt|Bentley|1989}} does not mention this difference, using <code>x</code> instead of <code>0</code> in the [[#No empty subarrays admitted|above]] version without empty subarrays achieves maintaining its loop invariant <code>current_sum</code><math>=\max_{i \in \{ 1, ..., j-1 \}} A[i]+...+A[j-1]</math> at the beginning of the <math>j</math>th step.
}}
<syntaxhighlight lang="python" line start="6">
current_sum = max(0, current_sum + x)
</syntaxhighlight>
 
As a [[loop invariant]], in the <math>j</math>th step, the old value of <code>current_sum</code> holds the maximum over all <math>i \in \{ 1,\ldots, j \}</math> of the sum <math>A[i]+\cdots+A[j-1]</math>.{{NoteTag
|This sum is <math>0</math> when <math>i=j</math>, corresponding to the empty subarray <math>A[j\ldots j-1]</math>.
}}
Therefore, <code>current_sum</code><math>+A[j]</math>
is the maximum over all <math>i \in \{ 1,\ldots, j \}</math> of the sum <math>A[i]+\cdots+A[j]</math>. To extend the latter maximum to cover also the case <math>i=j+1</math>, it is sufficient to consider also the empty subarray <math>A[j+1 \; \ldots \; j]</math>. This is done in line 6 by assigning <math>\max(0,</math><code>current_sum</code><math>+A[j])</math> as the new value of <code>current_sum</code>, which after that holds the maximum over all <math>i \in \{ 1, \ldots, j+1 \}</math> of the sum <math>A[i]+\cdots+A[j]</math>. Machine-verified [[C (programming language)|C]] / [[Frama-C]] code of both variants can be found [[:commons:File:Kadane run −2,1,−3,4,−1,2,1,−5,4.gif#Source code|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 <math>O(n)</math> and its space complexity is <math>O(1)</math>.{{sfn|Bentley|1989|p=74}}{{sfn|Gries|1982|p=211}}
 
== Generalizations ==
Similar problems may be posed for higher-dimensional arrays, but their solutions are more complicated; see, e.g., {{harvtxt|Takaoka|2002}}. {{harvtxt|Brodal|Jørgensen|2007}} showed how to find the ''k'' largest subarray sums in a one-dimensional array, in the optimal time bound <math>O(n + k)</math>.
 
The Maximum sum ''k''-disjoint subarrays can also be computed in the optimal time bound <math>O(n + k)</math>
.{{sfn|Bengtsson|Chen|2007}}
 
== See also ==
* [[Subset sum problem]]
 
==Notes==
{{NoteFoot|30em}}
 
==Notes==
{{Reflist}}
 
==References==
*{{citation
| firstlast1 = JonAlves | lastfirst1 = BentleyCarlos | authorlink = JonE. BentleyR.
| last2 = Cáceres | first2 = Edson
| title = Programming pearls: algorithm design techniques
| last3 = Song | first3 = Siang W.
| editor1-last = Kranzlmüller | editor1-first = Dieter
| editor2-last = Kacsuk | editor2-first = Péter
| editor3-last = Dongarra | editor3-first = Jack J.
| contribution = BSP/CGM Algorithms for Maximum Subsequence and Maximum Subarray
| doi = 10.1007/978-3-540-30218-6_24
| pages = 139–146
| publisher = Springer
| series = Lecture Notes in Computer Science
| title = Recent Advances in Parallel Virtual Machine and Message Passing Interface, 11th European PVM/MPI Users' Group Meeting, Budapest, Hungary, September 19-22, 2004, Proceedings
| volume = 3241
| year = 2004| isbn = 978-3-540-23163-9
}}
*{{citation
| last1 = Backurs
| first1 = Arturs
| last2 = Dikkala
| first2 = Nishanth
| last3 = Tzamos
| first3 = Christos
| date = 2016
| title = Tight Hardness Results for Maximum Weight Rectangles
| url =
| journal = Proc. 43rd International Colloquium on Automata, Languages, and Programming
| volume =
| issue =
| pages = 81:1–81:13
| doi = 10.4230/LIPIcs.ICALP.2016.81
| doi-access = free
| s2cid = 12720136
}}
*{{citation
| type=Ph.D. thesis
| url=https://pdfs.semanticscholar.org/bea4/1795adaf240b9db4195b9dc511bd8d46bff1.pdf
| archive-url=https://web.archive.org/web/20171026110814/https://pdfs.semanticscholar.org/bea4/1795adaf240b9db4195b9dc511bd8d46bff1.pdf
| url-status=dead
| archive-date=2017-10-26
| first=Sung Eun
| last=Bae
| title=Sequential and Parallel Algorithms for the Generalized Maximum Subarray Problem
| institution=University of Canterbury
| year=2007
| s2cid=2681670
}}.
*{{citation
| last1 = Bae | first1 = Sung Eun
| last2 = Takaoka | first2 = Tadao
| doi = 10.1093/COMJNL/BXL007
| issue = 3
| journal = The Computer Journal
| pages = 358–374
| title = Improved Algorithms for the \emph{K}-Maximum Subarray Problem
| volume = 49
| year = 2006}}
*{{citation
| last1=Bengtsson
| first1=Fredrik
| last2=Chen
| first2=Jingsen
| type=Research report
| date=2007
| title=Computing maximum-scoring segments optimally
| url=http://ltu.diva-portal.org/smash/get/diva2:995901/FULLTEXT01.pdf
| institution=Luleå University of Technology
| volume=
| issue=3
| pages=
| via=
}}
*{{citation
| first = Jon | last = Bentley
| authorlink = Jon Bentley (computer scientist)
| title = Programming Pearls: Algorithm Design Techniques
| journal = [[Communications of the ACM]]
| volume = 27 | issue = 9 | year = 1984
| pages = 865–873
| doi = 10.1145/358234.381162
| pagess2cid = 865–873207565329
}}.
 
*{{citation
| isbn=0-201-10331-1
| first1 = Gerth Stølting | last1 = Brodal | first2 = Allan Grønlund | last2 = Jørgensen
| first=Jon
| last=Bentley
| title=Programming Pearls
| ___location=Reading, MA
| publisher=Addison Wesley
| edition=2nd?
| date=May 1989
| url-access=registration
| url=https://archive.org/details/programmingpearl00bent
}}
*{{citation
| first=Richard S.
| last= Bird
| author-link=Richard S. Bird
| title=Algebraic Identities for Program Calculation
| journal=[[The Computer Journal]]
| volume=32
| number=2
| pages=122–126
| year=1989
| doi=10.1093/comjnl/32.2.122
}}
*{{citation
| first1 = Gerth Stølting | last1 = Brodal
| first2 = Allan Grønlund | last2 = Jørgensen
| title = Mathematical Foundations of Computer Science 2007
| contribution = A linear time algorithm for the ''k'' maximal sums problem
| title = Mathematical Foundations of Computer Science 2007
| publisher = Springer-Verlag
| series = Lecture Notes in Computer Science
| volume = 4708 | year = 2007 | pages = 442–453 | doi = 10.1007/978-3-540-74456-6_40}}.
| isbn = 978-3-540-74455-9
 
}}.
*{{citation
| url=https://core.ac.uk/download/pdf/82596333.pdf
| first = T. | last = Takaoka
| first=David
| last= Gries
| title=A Note on the Standard Strategy for Developing Loop Invariants and Loops
| journal=Science of Computer Programming
| volume=2
| pages=207&ndash;241
| year=1982
| issue=3
| doi=10.1016/0167-6423(83)90015-1
| hdl=1813/6370
}}
*{{citation
| last1 = Ruzzo | first1 = Walter L.
| last2 = Tompa | first2 = Martin
| editor1-last = Lengauer | editor1-first = Thomas
| editor2-last = Schneider | editor2-first = Reinhard
| editor3-last = Bork | editor3-first = Peer
| editor4-last = Brutlag | editor4-first = Douglas L.
| editor5-last = Glasgow | editor5-first = Janice I.
| editor6-last = Mewes | editor6-first = Hans-Werner
| editor7-last = Zimmer | editor7-first = Ralf
| contribution = A Linear Time Algorithm for Finding All Maximal Scoring Subsequences
| contribution-url = https://www.aaai.org/Library/ISMB/1999/ismb99-027.php
| pages = 234–241
| publisher = AAAI
| title = Proceedings of the Seventh International Conference on Intelligent Systems for Molecular Biology, August 6–10, 1999, Heidelberg, Germany
| year = 1999}}
*{{citation
| first = Tadao | last = Takaoka
| title = Efficient algorithms for the maximum subarray problem by distance matrix multiplication
| journal = Electronic Notes in Theoretical Computer Science | volume = 61 | yearpages = 2002191–200
| year = 2002
| url = http://www.cosc.canterbury.ac.nz/tad.takaoka/subarray.ps}}.
| doi = 10.1016/S1571-0661(04)00313-5
| doi-access = free
}}.
*{{citation
| last1 = Tamaki
| first1 = Hisao
| last2 = Tokuyama
| first2 = Takeshi
| date = 1998
| title = Algorithms for the Maximum Subarray Problem Based on Matrix Multiplication
| url = http://dl.acm.org/citation.cfm?id=314613.314823
| journal = Proceedings of the 9th Symposium on Discrete Algorithms (SODA)
| volume =
| issue =
| pages = 446–452
| doi =
| isbn = 978-0-89871-410-4
| access-date = November 17, 2018
}}
*{{citation
| last1 = Weddell | first1 = Stephen John
| last2 = Read | first2 = Tristan
| last3 = Thaher | first3 = Mohammed
| last4 = Takaoka | first4 = Tadao
| doi = 10.1117/1.JEI.22.4.043011
| issue = 4
| journal = Journal of Electronic Imaging
| page = 043011
| title = Maximum subarray algorithms for use in astronomical imaging
| volume = 22
| year = 2013| bibcode = 2013JEI....22d3011W
}}
 
== External links ==
* {{Cite web|url=http://www.picb.ac.cn/~xiaohang/vimwiki/study/tanlirong/Algorithm/project/Report.pdf|title=Maximum Contiguous Subarray Sum Problems|last=TAN|first=Lirong|access-date=2017-10-26|archive-url=https://web.archive.org/web/20151010072051/http://www.picb.ac.cn/~xiaohang/vimwiki/study/tanlirong/Algorithm/project/Report.pdf|archive-date=2015-10-10|url-status=dead}}
* [http://computationalthinking.googlepages.com/kadanealgorithm Kadane's Algorithm]
* {{Cite web|url=https://www.iis.sinica.edu.tw/~scm/2010/maximum-segment-sum-origin-and-derivation|title=The Maximum Segment Sum Problem: Its Origin, and a Derivation|date=2010|last=Mu|first=Shin-Cheng}}
* {{Cite web|url=http://cs.slu.edu/~goldwamh/courses/slu/csci314/2012_Fall/lectures/maxsubarray/|title=Notes on Maximum Subarray Problem|date=2012}}
* [http://www.algorithmist.com/index.php/Kadane's_Algorithm www.algorithmist.com]
* [http://alexeigor.wikidot.com/kadane alexeigor.wikidot.com]
* [http://rosettacode.org/wiki/Greatest_subsequential_sum greatest subsequential sum problem on Rosetta Code]
* [https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/ geeksforgeeks page on Kadane's Algorithm]
 
[[Category:Optimization algorithms and methods]]
[[Category:Dynamic programming]]
[[Category:ArticlesPolynomial-time with example Python codeproblems]]
[[Category:Articles with example Python (programming language) code]]