
- Aka Maximum Sum of Subarray
- Dynamic Programming
Maximum Subarray Problem
From Wikipedia
In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array, a[1…n], of numbers which has the largest sum.
The task is to find a subarray (contiguous elements) of the given array that has the largest sum. For instance:
1 |
[1, 5, -1, 0, 10] |
The answer would be 15 or the entire array (it’s also a subarray)
1 |
[0, -1, -5, 0, -4] |
The answer would be 0 and so on.
Solutions
Brute-force
All you need is going through all sub-arrays, keep the global maximum and compare.
Dynamic Programming (Kadane’s Algorithm)
O(n)runtime complexityO(1)space.
Following function shows the Kadane’s algorithm implementation which uses two variables, one to store the local maximum and the other to keep track of the global maximum:
1 |
def (A): |
So we assume that the largest subarray is the first element, then we go through A[1:] elements (all elements except the first one).
At each step, what we do is:
- Can current element plus the last largest sum_ help to find a largest subarray (line 4)?
- If yes, update the
max_ending_hereor our local maximum, otherwise current element is the largest subarray (array of one). - Then update the global maximum or
max_so_farif there is a new global maximum.
When the loop is over, return the global maximum.
Conclusion
Kadane’s algorithm is a Dynamic Programming approach to solve “the largest contiguous elements in an array” with runtime of O(n).




近期评论