/
Maximum  Subarray  Problem Maximum  Subarray  Problem

Maximum Subarray Problem - PowerPoint Presentation

mackenzie
mackenzie . @mackenzie
Follow
66 views
Uploaded On 2023-11-07

Maximum Subarray Problem - PPT Presentation

You can buy a unit of stock only one time then sell it at a later date Buysell at end of day Strategy buy low sell high The lowest price may appear after the highest price Assume you know future prices ID: 1030011

mid sum left subarray sum mid subarray left max sell high buy day find price divide maximum lowest highest

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Maximum Subarray Problem" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. Maximum Subarray ProblemYou can buy a unit of stock, only one time, then sell it at a later dateBuy/sell at end of dayStrategy: buy low, sell highThe lowest price may appear after the highest priceAssume you know future pricesCan you maximize profit by buying at lowest price and selling at highest price?

2. Buy lowest sell highest

3. Brute forceHow many buy/sell pairs are possible over n days?Evaluate each pair and keep track of maximumCan we do better?

4. TransformationFind sequence of days so that: the net change from last to first is maximizedLook at the daily change in priceChange on day i: price day i minus price day i-1We now have an array of changes (numbers), e.g.12,-3,-24,20,-3,-16,-23,18,20,-7,12,-5,-22,14,-4,6 Find contiguous subarray with largest summaximum subarrayE.g.: buy after day 7, sell after day 11

5. Brute force againTrivial if only positive numbers (assume not)Need to check O(n2) pairsFor each pair, find the sumThus total time is …

6. Divide-and-ConquerA[low..high]Divide in the middle: A[low,mid], A[mid+1,high]Any subarray A[i,..j] is(1) Entirely in A[low,mid](2) Entirely in A[mid+1,high](3) In both(1) and (2) can be found recursively

7. Divide-and-Conquer (cont.)(3) find maximum subarray that crosses midpointNeed to find maximum subarrays of the formA[i..mid], A[mid+1..j], low <= i, j <= high Take subarray with largest sum of (1), (2), (3)

8. 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 = jreturn (max-left, max-right, left-sum + right-sum)

9. Time analysisFind-Max-Cross-Subarray: O(n) timeTwo recursive calls on input size n/2Thus: T(n) = 2T(n/2) + O(n) T(n) = O(n log n)