Courses Next Semester
Algorithmic Paradigms
Divide and Conquer
Greedy
And now…
Compare to divide and conquer:
Recall the Fibonacci Sequence:
Defined by:
Recursive code:
Fib(n):
if n <= 2 then return 1
return Fib(n-1) + Fib(n-2)
Fib(n):
if n <= 2 then return 1
return Fib(n-1) + Fib(n-2)
Recursive subproblems overlap
Recursing without recursion
How to do for Fibonacci?
MFib(n):
a <- array of size n
a[1] <- 1
a[2] <- 1
for each index i from 3 to n do
a[i] <- a[i-1] + a[i-2]
endfor
return a[n]
MFib(n):
a <- array of size n
a[1] <- 1
a[2] <- 1
for each index i from 3 to n do
a[i] <- a[i-1] + a[i-2]
endfor
return a[n]
With memoization, we converted
into
Goal. Pick day $b$ to buy and day $s$ to sell to maximize profit.
Input. Array $a$ of size $n$
Output. Indices $b$ (buy) and $s$ (sell) with $1 \leq b \leq s \leq n$ that maximize profit
MaxProfit(a, i, j):
if j - i = 1 then return 0
m <- (i + j) / 2
left <- MaxProfit(a, i, m)
right <- MaxProfit(a, m, j)
min <- FindMin(a, i, m)
max <- FindMax(a, m, j)
return Max(left, right, max - min)
Running time?
Questions.
In case 1, how should we determine buy date?
In case 2, how should we compute max profit?
MaxProfit(a, n):
if n = 1 then return 0
min <- FindMin(a, n)
max <- MaxProfit(a, n-1)
return max(a[n] - min, max)
Running time?
What makes MaxProfit
inefficient?
What part(s) of the procedure can be memoized?
MaxProfit
Create two arrays:
min[i]
stores minimum value in a[1..i]
max[i]
stores maximum profit achievable by selling up to time i
Question. How to update these arrays?
MMaxProfit(a):
initialize arrays min, max
min[1] <- a[1]
max[1] <- 0
for i from 2 to n do
min[i] <- Min(min[i-1], a[i])
max[i] <- Max(max[i-1], a[i] - min[i])
endfor
return max[n]
Induction on $n$…
MMaxProfit(a):
initialize arrays min, max
min[1] <- a[1]
max[1] <- 0
for i from 2 to n do
min[i] <- Min(min[i-1], a[i])
max[i] <- Max(max[i-1], a[i] - min[i])
endfor
return max[n]
Can do without arrays for min
and max
MMaxProfit(a):
min <- a[1]
max <- 0
for i from 2 to n do
min <- Min(min, a[i])
max <- Max(max, a[i] - min)
endfor
return max[n]
Update MMaxProfit
to return the buy/sell days in addition to the maximum achievable profit.