0% found this document useful (0 votes)
10 views8 pages

Greedy Algorithms

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views8 pages

Greedy Algorithms

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Introduction to Algorithms

Greedy Algorithms
 Similar to dynamic programming, but simpler approach
 Also used for optimization problems
 Idea: When we have a choice to make, make the one
that looks best right now
 Make a locally optimal choice in hope of getting a globally optimal
solution
 Makes the choice that looks best at the moment in order
to get optimal solution.
Applications of Greedy
Algorithm
It is used in finding the shortest path.
 It is used to find the minimum spanning tree using the
prim's algorithm or the Kruskal's algorithm.
 It is used in a job sequencing with a deadline.
 This algorithm is also used to solve the fractional

knapsack problem.

3
Fractional Knapsack Problem
 Knapsack capacity: W
 There are n items: the i-th item has value vi and weight

wi
 Goal:
 find xi such that for all 0  xi  1, i = 1, 2, .., n

 wixi  W and

 xivi is maximum
Fractional Knapsack -
ExampleM=240

 E.g.: 20
---
$80
Item 3 30 +

Item 2 50 50
20 $100
Item 1 30
20 +
10 10 $60

$60 $100 $120 $240

$6/pound $5/pound $4/pound


Fractional Knapsack Problem
 Greedy strategy 1:
 Pick the item with the maximum value
 E.g.:
 W=1
 w1 = 100, v1 = 2
 w2 = 1, v2 = 1
 Taking from the item with the maximum value:
Total value taken = v1/w1 = 2/100
 Smaller than what the thief can take if choosing the
other item
Total value (choose item 2) = v2/w2 = 1
Fractional Knapsack Problem
Alg.: Fractional-Knapsack (W, v[n], w[n])

1. While w > 0 and as long as there are items remaining

2. pick item with maximum vi/wi

3. xi  min (1, w/wi)

4. remove item i from list

5. w  w – xiwi

 w – the amount of space remaining in the knapsack (w = W)


 Running time: (n) if items already ordered; else (nlgn)
Dynamic Programming vs. Greedy
Algorithms
 Dynamic programming

 We make a choice at each step


 The choice depends on solutions to subproblems
 Bottom up solution, from smaller to larger subproblems
 Greedy algorithm
 Make the greedy choice and THEN
 Solve the subproblem arising after the choice is made
 The choice we make may depend on previous choices,
but not on solutions to subproblems
 Top down solution, problems decrease in size

You might also like