CSC6023 Week4-Neff
CSC6023 Week4-Neff
CSC6023 Week4-Neff
Greedy algorithms -
Week 4
Patrick Neff
Half of the
course
Week 4
Greedy
Algorithms
Greedy
Algorithms
1 1
Computer Algorithms
A Non Greedy Approach
1 1
Examples
The problem
Egyptian ● Starts with the largest possible fitting unit fraction, than
Fractions deal with the remainder (recursively)
○ For example: 7/15
■ ½ won't fit, ⅓ fits!
○ 7/15 = 1/3 + ? => 7/15 = 5/15 + 2/15
■ Apply it to 2/15:
● ½, ⅓, ¼, ⅕, ⅙, and 1/7 won't fit, ⅛ fits!
○ 7/15 = 1/3 + 1/8 + ? => 56/120 = 40/120 + 15/120 + 1/120
■ Apply it to 1/120 (elementary solution)
○ 7/15 = 1/3 + 1/8 + 1/120 (final solution)
Examples
The Greedy solution - Python implementation
Egyptian
Fractions
Egyptian
Fractions
Egyptian
Fractions
Egyptian
● The fraction 5/121 if computed correctly should
Fractions be
Knapsack
Problem
● Compute item's ratio
between weight and value
● Sort the elements by the
ratio (non decrescent)
● Repeatedly pick the item
with highest ratio that fits
the maximum weight
capacity
Examples
The Solution - Greedy approach
Knapsack
Problem
● Get the number
of items, plus
their value and
weight
● Get the capacity
● Call knapsack