Lecture 34
Lecture 34
Greedy Algorithms
designing algorithms
Use when problem breaks down into recurring
small subproblems
than once
Memoization
Memoization is another way to deal with overlapping
subproblems
After computing the solution to a subproblem, store in a table
Subsequent calls just do a table lookup
running space?
O(min(m,n))
Greedy Algorithms
A greedy algorithm always makes the choice that
optimal solution
For some problems, it works
Dynamic programming can be overkill; greedy
Activity-Selection Problem
Problem: get your moneys worth out of a
carnival
Buy a wristband that lets you onto any ride
Lots of rides, each starting and ending at different
times
Your goal: ride as many rides as possible
Another, alternative goal that we dont solve here:
Activity-Selection
Formally:
Given a set S of n activities
2
5
Activity Selection:
Optimal Substructure
Let k be the minimum activity in A (i.e., the one
reduces to finding an optimal solution for activityselection over activities in S compatible with #1
Proof: if we could find optimal solution B to S with |B|
> |A - {k}|,
Then B U {k} is compatible
And |B U {k}| > |A|
Activity Selection:
Repeated Subproblems
Consider a recursive algorithm that tries all
yes
S
S
2A?
no
S-{2}
S
1A?
no
yes
S
S-{1}
2A?
no
S-{1,2}
choice property:
Locally optimal choice globally optimal soln
Them 17.1: if S is an activity selection problem sorted
Activity Selection:
A Greedy Algorithm
So actual algorithm is simple:
Sort the activities by finish time
Schedule the first activity
Then schedule the next activity in sorted list which
Review:
The Knapsack Problem
The famous knapsack problem:
A thief breaks into a museum. Fabulous paintings,
greedy approach
As you have seen, however, it can be solved with
dynamic programming