Given an array, kadane's algorithm finds a contiguous subarray with the largest sum.
Kadane's algorithm uses dynamic programming. However, implementing maximum subarray using divide & conquer is more subtle. We can split the array by half at each step and compute the following subproblem falling into 3 cases:
- The maximum subarray falls into the left half of the array
- The maximum subarray falls into the right half of the array
- The maximum subarray goes through the middle of the array being the sum of the left half and the right half
Best Case: Ω(n)
Average Case: θ(n)
Worst Case: O(n)
where n represents the size of the array.
Worst Case: O(1)
The function maximum_subarray
has the following parameter(s):
a
: a vector of integers
Return value: The maximum subarray sum.
The first line contains an integer n
, the size of array.
The next line contains n
space-separated integers a[i]
where 0 ≤ i
< n
.
An integer representing the maximum subarray sum.
5
5 1 3 4 2
15
Since all numbers in the array are positive, the maximum subarray is the sum of all elements.
which is 5 + 1 + 3 + 4 + 2 = 15.
5
-2 4 -3 5 -1
6
The maximum subarray can be formed as follows:
4 + (-3) + 5 = 6, which is the largest possible.
5
-4 -3 -1 -2 -5
0
Since all numbers in the array are negative, the maximum subarray is 0 by not including any elements or the empty subarray.