Knapsack
Knapsack
Greedy Methods
2
Greedy Method
• A greedy algorithm is an approach for solving a problem by selecting the
best option available at the moment. It doesn't worry whether the current
best result will bring the overall optimal result.
• The algorithm never reverses the earlier decision even if the choice is
wrong. It works in a top-down approach.
• This algorithm may not produce the best result for all the problems. It's
because it always goes for the local best choice to produce the global best
result.
3
Greedy Method
• However, we can determine if the algorithm can be used with any problem
if the problem has the following properties:
4
Greedy Method
2. Optimal Substructure
5
Greedy Method
• Applications:
• Knapsack
• Job Sequencing
• Minimum Spanning Tree
• Huffman Coding
• Dijkstra Algorithm
• Optimal Merge Pattern
6
Knapsack Problem
The classic Knapsack problem is:
A thief breaks into a store and wants to fill his knapsack of capacity K with
goods of as much value as possible.
Decision version: Does there exist a collection of items that fits into his
knapsack and whose total value is maximized ?
• Input
• Capacity K
• n items with weights wi and values vi
• Output: a set of items S such that
• the sum of weights of items in S is at most K
• and the sum of values of items in S is maximized
7
Fractional Knapsack Problem
8
Fractional Knapsack Procedure
1. Sort the items in the ascending order of value/weight ratio (cost
effectiveness).
2. If the next item cannot fit into the knapsack, break it and pick it
partially just to fill the knapsack.
• n objects, each with a weight wi > 0
a profit pi > 0
capacity of knapsack: M
Maximize å pi xi
1£ i £ n
Subject to å w i xi £ M
1£ i £ n
0 £ xi £ 1, 1 £ i £ n
9
Knapsack Example
Object (X): 1 2 3 n = 3, Algorithm
Knapsack Capacity M = 20
Profit (P): 25 24 15 for i to n
Calculate Profit / Weight
Weight (W): 18 15 10 Sort objects in decreasing
order of p/w ratio
P/W : 1.32 1.6 1.5
n = 4,
M = 23
11
THANK YOU
12