Maximum Subarray Problem: - You Can Buy A Unit of Stock, Only One Time, Then Sell It at A Later Date
Maximum Subarray Problem: - You Can Buy A Unit of Stock, Only One Time, Then Sell It at A Later Date
You can buy a unit of stock, only one time, then sell it
at a later date
Buy/sell at end of day
Brute force
How many buy/sell pairs are possible
over n days?
Evaluate each pair and keep track of
maximum
Can we do better?
Transformation
Find sequence of days so that:
the net change from last to first is maximized
Divide-and-Conquer
A[low..high]
Divide in the middle:
A[low,mid], A[mid+1,high]
Divide-and-Conquer (cont.)
(3) find maximum subarray that
crosses midpoint
Need to find maximum subarrays of the
form
A[i..mid], A[mid+1..j], low <= i, j <= high
Divide-and-Conquer (cont.)
Find-Max-Cross-Subarray(A,low,mid,high)
left-sum = -
sum = 0
for i = mid downto low
sum = sum + A[i]
if sum > left-sum then
left-sum = sum
max-left = i
right-sum = -
sum = 0
for j = mid+1 to high
sum = sum + A[j]
if sum > right-sum then
right-sum = sum
max-right = j
return (max-left, max-right, left-sum + right-sum)
Time analysis
Find-Max-Cross-Subarray: O(n) time
Two recursive calls on input size n/2
Thus:
T(n) = 2T(n/2) + O(n)
T(n) = O(n log n)