In short:
Let A
be an array of length n
. You want to compute the max subarray of A
sou you call Find-Maximum-Subarray(A, 0, n-1)
. Now try to make the problem easier:
- Case. high = low:
In this case the Array has only 1 Element so the solution is simple high != low
In this case the solutions are to hard to find. so try to make the problem smaller. What happens if we cut the arrayA
into arraysB1
andB2
of the half length. Now there are only 3 new casesa) the Max Subarray of
A
is also a subarray ofB1
but not ofB2
b) The max subarray ofA
is also a subarray ofB2
but not ofB1
c) The max subarray ofA
overlaps withB1
andB2
so you compute the max subarray of
B1
andB2
separately and look for an overlapping solution and finally you take the largest one.
The trick is now, that you can du the same thing with B1
and B2
.
Example:
A =[-1, 2, -1, 1]
Call Find-Maximum-Subarray(A, 0, 3);
- Call Find-Maximum-Subarray(A, 0, 1); -> returns ( 1, 1, 2 ) (cause 2 > 1 > -1, see the subcalls)
- Call Find-Maximum-Subarray(A, 0, 0); -> returns ( 0, 0, -1 )
- Call Find-Maximum-Subarray(A, 1, 1); -> returns ( 1, 1, 2 )
- Call Find-Max-Crossing-Subarray(A, 0, 0, 1); -> returns ( 0, 1, 1 )
- Call Find-Maximum-Subarray(A, 2, 3); -> returns ( 3, 3, 1 ) ( 1 > 0 > -1, see subcalls)
- Call Find-Maximum-Subarray(A, 2, 2); -> returns ( 2, 2, -1 )
- Call Find-Maximum-Subarray(A, 3, 3); -> returns ( 3, 3, 1 )
- Call Find-Max-Crossing-Subarray(A, 2, 2, 3); returns ( 2, 3, 0 )
- Call Find-Max-Crossing-Subarray(A, 0, 1, 3); -> returns ( 1, 3, 2 )
- Here you have to take at least the elements A[1] and A[2] with the sum of 1,
but if you also take A[3]=1 the sum will be 2. taking A[0] does not help
due to A[0] is negative
- Now you have only to look which subarray has the larger sum. In this case you
have two with the same size: A[1] and A[1-3]. Return one of them.