SlideShare a Scribd company logo
KNAPSACK PROBLEM AND MEMORY
FUNCTION
PREPARED BY
M. Baranitharan
Kings College of Engineering
Given some items, pack the knapsack to get
the maximum total value. Each item has some
weight and some value. Total weight that we can
carry is no more than some fixed number W.
So we must consider weights of items as well as
their values.
Item # Weight Value
1 1 8
2 3 6
3 5 5
There are two versions of the problem:
1. “0-1 knapsack problem”
 Items are indivisible; you either take an item or not.
Some special instances can be solved with dynamic
programming
1. “Fractional knapsack problem”
 Items are divisible: you can take any fraction of an
item
 Given a knapsack with maximum capacity W, and
a set S consisting of n items
 Each item i has some weight wi and benefit value
bi (all wi and W are integer values)
 Problem: How to pack the knapsack to achieve
maximum total value of packed items?
 Problem, in other words, is to find
∑∑ ∈∈
≤
Ti
i
Ti
i Wwb subject tomax
The problem is called a “0-1” problem,
because each item must be entirely
accepted or rejected.
Let’s first solve this problem with a
straightforward algorithm
 Since there are n items, there are 2n
possible
combinations of items.
 We go through all combinations and find the
one with maximum value and with total weight
less or equal to W
 Running time will be O(2n
)
 We can do better with an algorithm based on
dynamic programming
 We need to carefully identify the subproblems
 Given a knapsack with maximum capacity W, and
a set S consisting of n items
 Each item i has some weight wi and benefit value
bi (all wi and W are integer values)
 Problem: How to pack the knapsack to achieve
maximum total value of packed items?
 We can do better with an algorithm based on
dynamic programming
 We need to carefully identify the subproblems
Let’s try this:
If items are labeled 1..n, then a subproblem
would be to find an optimal solution for
Sk = {items labeled 1, 2, .. k}
If items are labeled 1..n, then a subproblem
would be to find an optimal solution for Sk =
{items labeled 1, 2, .. k}
 This is a reasonable subproblem definition.
 The question is: can we describe the final
solution (Sn ) in terms of subproblems (Sk)?
 Unfortunately, we can’t do that.
Max weight: W = 20
For S4:
Total weight: 14
Maximum benefit: 20
w1 =2
b1 =3
w2 =4
b2 =5
w3 =5
b3 =8
w4 =3
b4 =4 wi bi
10
85
54
43
32
Weight Benefit
9
Item
#
4
3
2
1
5
S4
S5
w1 =2
b1 =3
w2 =4
b2 =5
w3 =5
b3 =8
w5 =9
b5 =10
For S5:
Total weight: 20
Maximum benefit: 26
Solution for S4 is
not part of the
solution for S !!!
?
 As we have seen, the solution for S4 is not part of
the solution for S5
 So our definition of a subproblem is flawed and we
need another one!
 Given a knapsack with maximum capacity W, and
a set S consisting of n items
 Each item i has some weight wi and benefit value
bi (all wi and W are integer values)
 Problem: How to pack the knapsack to achieve
maximum total value of packed items?
 Let’s add another parameter: w, which will
represent the maximum weight for each subset of
items
 The subproblem then will be to compute V[k,w],
i.e., to find an optimal solution for Sk = {items
labeled 1, 2, .. k} in a knapsack of size w
 The subproblem will then be to compute V[k,w],
i.e., to find an optimal solution for Sk = {items
labeled 1, 2, .. k} in a knapsack of size w
 Assuming knowing V[i, j], where i=0,1, 2, … k-1,
j=0,1,2, …w, how to derive V[k,w]?
It means, that the best subset of Sk that has total
weight w is:
1) the best subset of Sk-1 that has total weight ≤ w, or
2) the best subset of Sk-1 that has total weight ≤ w-wk plus
the item k



+−−−
>−
=
else}],1[],,1[max{
if],1[
],[
kk
k
bwwkVwkV
wwwkV
wkV
Recursive formula for subproblems:
 The best subset of Sk that has the total weight ≤ w,
either contains item k or not.
 First case: wk>w. Item k can’t be part of the solution,
since if it was, the total weight would be > w, which is
unacceptable.
 Second case: wk ≤ w. Then the item k can be in the
solution, and we choose the case with greater value.



+−−−
>−
=
else}],1[],,1[max{
if],1[
],[
kk
k
bwwkVwkV
wwwkV
wkV
for w = 0 to W
V[0,w] = 0
for i = 1 to n
V[i,0] = 0
for i = 1 to n
for w = 0 to W
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
for w = 0 to W
V[0,w] = 0
for i = 1 to n
V[i,0] = 0
for i = 1 to n
for w = 0 to W
< the rest of the code >
What is the running time of this
algorithm?
O(W)
O(W)
Repeat n times
O(n*W)
Remember that the brute-force algorithm
takes O(2n
)
Let’s run our algorithm on the
following data:
n = 4 (# of elements)
W = 5 (max weight)
Elements (weight, benefit):
(2,3), (3,4), (4,5), (5,6)
for w = 0 to W
V[0,w] = 0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
for i = 1 to n
V[i,0] = 0
0
0
0
0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
0
Items:
1: (2,3)
2: (3,4)
3: (4,5)
4: (5,6)
0
i=1
bi=3
wi=2
w=1
w-wi =-1
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
0
0
0
Items:
1: (2,3)
2: (3,4)
3: (4,5)
4: (5,6)
300
0
0
0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
i=1
bi=3
wi=2
w=4
w-wi =2
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
3 3
Items:
1: (2,3)
2: (3,4)
3: (4,5)
4: (5,6)
300
0
0
0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
i=1
bi=3
wi=2
w=5
w-wi =3
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
3 3 3
Items:
1: (2,3)
2: (3,4)
3: (4,5)
4: (5,6)
00
0
0
0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
i=2
bi=4
wi=3
w=2
w-wi =-1
3 3 3 3
3
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
0
Items:
1: (2,3)
2: (3,4)
3: (4,5)
4: (5,6)
00
0
0
0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
i=2
bi=4
wi=3
w=3
w-wi =0
3 3 3 3
0
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
43
Items:
1: (2,3)
2: (3,4)
3: (4,5)
4: (5,6)
00
0
0
0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
i=3
bi=5
wi=4
w= 1..3
3 3 3 3
0 3 4 4
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
7
3 40
Items:
1: (2,3)
2: (3,4)
3: (4,5)
4: (5,6)
00
0
0
0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
i=4
bi=6
wi=5
w= 1..4
3 3 3 3
0 3 4 4
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
7
3 40
70 3 4 5
5
Items:
1: (2,3)
2: (3,4)
3: (4,5)
4: (5,6)
00
0
0
0
0 0 0 0 000
1
2
3
4 50 1 2 3
4
iW
i=4
bi=6
wi=5
w= 5
w- wi=0
3 3 3 3
0 3 4 4 7
0 3 4
if wi <= w // item i can be part of the solution
if bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w- wi]
else
V[i,w] = V[i-1,w]
else V[i,w] = V[i-1,w] // wi > w
5
7
7
0 3 4 5
 This algorithm only finds the max possible value
that can be carried in the knapsack
◦ i.e., the value in V[n,W]
 To know the items that make this maximum value,
an addition to this algorithm is necessary
 All of the information we need is in the table.
 V[n,W] is the maximal value of items that can be
placed in the Knapsack.
 Let i=n and k=W
if V[i,k] ≠ V[i−1,k] then
mark the ith
item as in the knapsack
i = i−1, k = k-wi
else
i = i−1 // Assume the ith
item is not in the knapsack
// Could it be in the optimally packed
knapsack?
 Goal:
◦ Solve only subproblems that are necessary and solve it only once
 Memorization is another way to deal with overlapping subproblems
in dynamic programming
 With memorization, we implement the algorithm recursively:
◦ If we encounter a new subproblem, we compute and store the solution.
◦ If we encounter a subproblem we have seen, we look up the answer
 Most useful when the algorithm is easiest to implement recursively
◦ Especially if we do not need solutions to all subproblems.
for i = 1 to n
for w = 1 to W
V[i,w] = -1
for w = 0 to W
V[0,w] = 0
for i = 1 to n
V[i,0] = 0
MFKnapsack(i, w)
if V[i,w] < 0
if w < wi
value = MFKnapsack(i-1, w)
else
value = max(MFKnapsack(i-1, w),
bi + MFKnapsack(i-1, w-wi))
V[i,w] = value
return V[i,w]
 Dynamic programming is a useful technique of
solving certain kind of problems
 When the solution can be recursively described
in terms of partial solutions, we can store these
partial solutions and re-use them as necessary
(memorization)
 Running time of dynamic programming
algorithm vs. naïve algorithm:
◦ 0-1 Knapsack problem: O(W*n) vs. O(2n
)
Design and Analysis of Algorithms - Chapter 8 36

More Related Content

What's hot

knapsack problem
knapsack problemknapsack problem
knapsack problem
Adnan Malak
 
Knapsack problem using dynamic programming
Knapsack problem using dynamic programmingKnapsack problem using dynamic programming
Knapsack problem using dynamic programming
khush_boo31
 
0-1 KNAPSACK PROBLEM
0-1 KNAPSACK PROBLEM0-1 KNAPSACK PROBLEM
0-1 KNAPSACK PROBLEM
i i
 
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
Mrunal Patil
 
Fractional Knapsack Problem
Fractional Knapsack ProblemFractional Knapsack Problem
Fractional Knapsack Problem
harsh kothari
 
Knapsack problem dynamicprogramming
Knapsack problem dynamicprogrammingKnapsack problem dynamicprogramming
Knapsack problem dynamicprogramming
rowntu
 
0 1 knapsack using branch and bound
0 1 knapsack using branch and bound0 1 knapsack using branch and bound
0 1 knapsack using branch and bound
Abhishek Singh
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
sandeep54552
 
Traveling salesman problem
Traveling salesman problemTraveling salesman problem
Traveling salesman problem
Jayesh Chauhan
 
Fractional knapsack class 13
Fractional knapsack class 13Fractional knapsack class 13
Fractional knapsack class 13
Kumar
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
Mohd Arif
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
Lemia Algmri
 
Sum of subset problem.pptx
Sum of subset problem.pptxSum of subset problem.pptx
Sum of subset problem.pptx
V.V.Vanniaperumal College for Women
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
Rajendran
 
Np hard
Np hardNp hard
Np hard
jesal_joshi
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
Dr Shashikant Athawale
 
finding Min and max element from given array using divide & conquer
finding Min and max element from given array using  divide & conquer finding Min and max element from given array using  divide & conquer
finding Min and max element from given array using divide & conquer
Swati Kulkarni Jaipurkar
 
Np completeness
Np completenessNp completeness
Np completeness
Rajendran
 
Tower Of Hanoi
Tower Of HanoiTower Of Hanoi
Tower Of Hanoi
Vinit Dantkale
 
All pair shortest path
All pair shortest pathAll pair shortest path
All pair shortest path
Arafat Hossan
 

What's hot (20)

knapsack problem
knapsack problemknapsack problem
knapsack problem
 
Knapsack problem using dynamic programming
Knapsack problem using dynamic programmingKnapsack problem using dynamic programming
Knapsack problem using dynamic programming
 
0-1 KNAPSACK PROBLEM
0-1 KNAPSACK PROBLEM0-1 KNAPSACK PROBLEM
0-1 KNAPSACK PROBLEM
 
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
 
Fractional Knapsack Problem
Fractional Knapsack ProblemFractional Knapsack Problem
Fractional Knapsack Problem
 
Knapsack problem dynamicprogramming
Knapsack problem dynamicprogrammingKnapsack problem dynamicprogramming
Knapsack problem dynamicprogramming
 
0 1 knapsack using branch and bound
0 1 knapsack using branch and bound0 1 knapsack using branch and bound
0 1 knapsack using branch and bound
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Traveling salesman problem
Traveling salesman problemTraveling salesman problem
Traveling salesman problem
 
Fractional knapsack class 13
Fractional knapsack class 13Fractional knapsack class 13
Fractional knapsack class 13
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Sum of subset problem.pptx
Sum of subset problem.pptxSum of subset problem.pptx
Sum of subset problem.pptx
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Np hard
Np hardNp hard
Np hard
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
finding Min and max element from given array using divide & conquer
finding Min and max element from given array using  divide & conquer finding Min and max element from given array using  divide & conquer
finding Min and max element from given array using divide & conquer
 
Np completeness
Np completenessNp completeness
Np completeness
 
Tower Of Hanoi
Tower Of HanoiTower Of Hanoi
Tower Of Hanoi
 
All pair shortest path
All pair shortest pathAll pair shortest path
All pair shortest path
 

Similar to Knapsack problem and Memory Function

DynProg_Knapsack.ppt
DynProg_Knapsack.pptDynProg_Knapsack.ppt
DynProg_Knapsack.ppt
Ruchika Sinha
 
Knapsack Dynamic
Knapsack DynamicKnapsack Dynamic
Knapsack Dynamic
Paras Patel
 
lecture 25
lecture 25lecture 25
lecture 25
sajinsc
 
Presentation of knapsack
Presentation of knapsackPresentation of knapsack
Presentation of knapsack
Gaurav Dubey
 
Design and analysis of Algorithms - Lecture 15.ppt
Design and analysis of Algorithms - Lecture 15.pptDesign and analysis of Algorithms - Lecture 15.ppt
Design and analysis of Algorithms - Lecture 15.ppt
QurbanAli72
 
0 1 knapsack using naive recursive approach and top-down dynamic programming ...
0 1 knapsack using naive recursive approach and top-down dynamic programming ...0 1 knapsack using naive recursive approach and top-down dynamic programming ...
0 1 knapsack using naive recursive approach and top-down dynamic programming ...
Abhishek Singh
 
0-1 knapsack.ppt
0-1 knapsack.ppt0-1 knapsack.ppt
0-1 knapsack.ppt
AyushJaiswal513854
 
AOA ppt.ppt
AOA ppt.pptAOA ppt.ppt
AOA ppt.ppt
SaimaShaheen14
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
garishma bhatia
 
Dynamic Programming knapsack 0 1
Dynamic Programming knapsack 0 1Dynamic Programming knapsack 0 1
Dynamic Programming knapsack 0 1
Amit Kumar Rathi
 
Greedy algo revision 2
Greedy algo revision 2Greedy algo revision 2
Greedy algo revision 2
maamir farooq
 
INNER_SPACE_PRODUCT-EUCLIDEAN_PLANE.pptx
INNER_SPACE_PRODUCT-EUCLIDEAN_PLANE.pptxINNER_SPACE_PRODUCT-EUCLIDEAN_PLANE.pptx
INNER_SPACE_PRODUCT-EUCLIDEAN_PLANE.pptx
AvilosErgelaKram
 
Dynamic Programming for 4th sem cse students
Dynamic Programming for 4th sem cse studentsDynamic Programming for 4th sem cse students
Dynamic Programming for 4th sem cse students
DeepakGowda357858
 
Comparative analysis-of-dynamic-and-greedy-approaches-for-dynamic-programming
Comparative analysis-of-dynamic-and-greedy-approaches-for-dynamic-programmingComparative analysis-of-dynamic-and-greedy-approaches-for-dynamic-programming
Comparative analysis-of-dynamic-and-greedy-approaches-for-dynamic-programming
Editor IJMTER
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Melaku Bayih Demessie
 
Module 3_DAA (2).pptx
Module 3_DAA (2).pptxModule 3_DAA (2).pptx
Module 3_DAA (2).pptx
AnkitaVerma776806
 
knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandbound
hodcsencet
 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy Method
DevaKumari Vijay
 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamic
chidabdu
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
rupali_2bonde
 

Similar to Knapsack problem and Memory Function (20)

DynProg_Knapsack.ppt
DynProg_Knapsack.pptDynProg_Knapsack.ppt
DynProg_Knapsack.ppt
 
Knapsack Dynamic
Knapsack DynamicKnapsack Dynamic
Knapsack Dynamic
 
lecture 25
lecture 25lecture 25
lecture 25
 
Presentation of knapsack
Presentation of knapsackPresentation of knapsack
Presentation of knapsack
 
Design and analysis of Algorithms - Lecture 15.ppt
Design and analysis of Algorithms - Lecture 15.pptDesign and analysis of Algorithms - Lecture 15.ppt
Design and analysis of Algorithms - Lecture 15.ppt
 
0 1 knapsack using naive recursive approach and top-down dynamic programming ...
0 1 knapsack using naive recursive approach and top-down dynamic programming ...0 1 knapsack using naive recursive approach and top-down dynamic programming ...
0 1 knapsack using naive recursive approach and top-down dynamic programming ...
 
0-1 knapsack.ppt
0-1 knapsack.ppt0-1 knapsack.ppt
0-1 knapsack.ppt
 
AOA ppt.ppt
AOA ppt.pptAOA ppt.ppt
AOA ppt.ppt
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
 
Dynamic Programming knapsack 0 1
Dynamic Programming knapsack 0 1Dynamic Programming knapsack 0 1
Dynamic Programming knapsack 0 1
 
Greedy algo revision 2
Greedy algo revision 2Greedy algo revision 2
Greedy algo revision 2
 
INNER_SPACE_PRODUCT-EUCLIDEAN_PLANE.pptx
INNER_SPACE_PRODUCT-EUCLIDEAN_PLANE.pptxINNER_SPACE_PRODUCT-EUCLIDEAN_PLANE.pptx
INNER_SPACE_PRODUCT-EUCLIDEAN_PLANE.pptx
 
Dynamic Programming for 4th sem cse students
Dynamic Programming for 4th sem cse studentsDynamic Programming for 4th sem cse students
Dynamic Programming for 4th sem cse students
 
Comparative analysis-of-dynamic-and-greedy-approaches-for-dynamic-programming
Comparative analysis-of-dynamic-and-greedy-approaches-for-dynamic-programmingComparative analysis-of-dynamic-and-greedy-approaches-for-dynamic-programming
Comparative analysis-of-dynamic-and-greedy-approaches-for-dynamic-programming
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Module 3_DAA (2).pptx
Module 3_DAA (2).pptxModule 3_DAA (2).pptx
Module 3_DAA (2).pptx
 
knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandbound
 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy Method
 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamic
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 

More from Barani Tharan

Graph coloring
Graph coloringGraph coloring
Graph coloring
Barani Tharan
 
Elliptical curve cryptography
Elliptical curve cryptographyElliptical curve cryptography
Elliptical curve cryptography
Barani Tharan
 
Water pollution parameter
Water pollution parameterWater pollution parameter
Water pollution parameter
Barani Tharan
 
Realism in Computer Graphics
Realism in Computer GraphicsRealism in Computer Graphics
Realism in Computer Graphics
Barani Tharan
 
Conjestion control
Conjestion controlConjestion control
Conjestion control
Barani Tharan
 
Networking in cloud computing
Networking in cloud computingNetworking in cloud computing
Networking in cloud computing
Barani Tharan
 
E book management system
E book management systemE book management system
E book management system
Barani Tharan
 
Energy band theory of solids
Energy band theory of solidsEnergy band theory of solids
Energy band theory of solids
Barani Tharan
 
Course registration system
Course registration systemCourse registration system
Course registration system
Barani Tharan
 
Clipping in Computer Graphics
Clipping in Computer Graphics Clipping in Computer Graphics
Clipping in Computer Graphics
Barani Tharan
 
Water indicator Circuit to measure the level of any liquid
Water indicator Circuit to measure the level of any liquidWater indicator Circuit to measure the level of any liquid
Water indicator Circuit to measure the level of any liquid
Barani Tharan
 
Cloud computing in medical field
Cloud computing in medical fieldCloud computing in medical field
Cloud computing in medical field
Barani Tharan
 
Application of fourier transform
Application of fourier transformApplication of fourier transform
Application of fourier transform
Barani Tharan
 
4G technology
4G technology4G technology
4G technology
Barani Tharan
 

More from Barani Tharan (14)

Graph coloring
Graph coloringGraph coloring
Graph coloring
 
Elliptical curve cryptography
Elliptical curve cryptographyElliptical curve cryptography
Elliptical curve cryptography
 
Water pollution parameter
Water pollution parameterWater pollution parameter
Water pollution parameter
 
Realism in Computer Graphics
Realism in Computer GraphicsRealism in Computer Graphics
Realism in Computer Graphics
 
Conjestion control
Conjestion controlConjestion control
Conjestion control
 
Networking in cloud computing
Networking in cloud computingNetworking in cloud computing
Networking in cloud computing
 
E book management system
E book management systemE book management system
E book management system
 
Energy band theory of solids
Energy band theory of solidsEnergy band theory of solids
Energy band theory of solids
 
Course registration system
Course registration systemCourse registration system
Course registration system
 
Clipping in Computer Graphics
Clipping in Computer Graphics Clipping in Computer Graphics
Clipping in Computer Graphics
 
Water indicator Circuit to measure the level of any liquid
Water indicator Circuit to measure the level of any liquidWater indicator Circuit to measure the level of any liquid
Water indicator Circuit to measure the level of any liquid
 
Cloud computing in medical field
Cloud computing in medical fieldCloud computing in medical field
Cloud computing in medical field
 
Application of fourier transform
Application of fourier transformApplication of fourier transform
Application of fourier transform
 
4G technology
4G technology4G technology
4G technology
 

Recently uploaded

14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
JamalHussainArman
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
mamunhossenbd75
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
Divyam548318
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
RadiNasr
 
2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt
PuktoonEngr
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
nooriasukmaningtyas
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 

Recently uploaded (20)

14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
 
2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 

Knapsack problem and Memory Function

  • 1. KNAPSACK PROBLEM AND MEMORY FUNCTION PREPARED BY M. Baranitharan Kings College of Engineering
  • 2. Given some items, pack the knapsack to get the maximum total value. Each item has some weight and some value. Total weight that we can carry is no more than some fixed number W. So we must consider weights of items as well as their values. Item # Weight Value 1 1 8 2 3 6 3 5 5
  • 3. There are two versions of the problem: 1. “0-1 knapsack problem”  Items are indivisible; you either take an item or not. Some special instances can be solved with dynamic programming 1. “Fractional knapsack problem”  Items are divisible: you can take any fraction of an item
  • 4.  Given a knapsack with maximum capacity W, and a set S consisting of n items  Each item i has some weight wi and benefit value bi (all wi and W are integer values)  Problem: How to pack the knapsack to achieve maximum total value of packed items?
  • 5.  Problem, in other words, is to find ∑∑ ∈∈ ≤ Ti i Ti i Wwb subject tomax The problem is called a “0-1” problem, because each item must be entirely accepted or rejected.
  • 6. Let’s first solve this problem with a straightforward algorithm  Since there are n items, there are 2n possible combinations of items.  We go through all combinations and find the one with maximum value and with total weight less or equal to W  Running time will be O(2n )
  • 7.  We can do better with an algorithm based on dynamic programming  We need to carefully identify the subproblems
  • 8.  Given a knapsack with maximum capacity W, and a set S consisting of n items  Each item i has some weight wi and benefit value bi (all wi and W are integer values)  Problem: How to pack the knapsack to achieve maximum total value of packed items?
  • 9.  We can do better with an algorithm based on dynamic programming  We need to carefully identify the subproblems Let’s try this: If items are labeled 1..n, then a subproblem would be to find an optimal solution for Sk = {items labeled 1, 2, .. k}
  • 10. If items are labeled 1..n, then a subproblem would be to find an optimal solution for Sk = {items labeled 1, 2, .. k}  This is a reasonable subproblem definition.  The question is: can we describe the final solution (Sn ) in terms of subproblems (Sk)?  Unfortunately, we can’t do that.
  • 11. Max weight: W = 20 For S4: Total weight: 14 Maximum benefit: 20 w1 =2 b1 =3 w2 =4 b2 =5 w3 =5 b3 =8 w4 =3 b4 =4 wi bi 10 85 54 43 32 Weight Benefit 9 Item # 4 3 2 1 5 S4 S5 w1 =2 b1 =3 w2 =4 b2 =5 w3 =5 b3 =8 w5 =9 b5 =10 For S5: Total weight: 20 Maximum benefit: 26 Solution for S4 is not part of the solution for S !!! ?
  • 12.  As we have seen, the solution for S4 is not part of the solution for S5  So our definition of a subproblem is flawed and we need another one!
  • 13.  Given a knapsack with maximum capacity W, and a set S consisting of n items  Each item i has some weight wi and benefit value bi (all wi and W are integer values)  Problem: How to pack the knapsack to achieve maximum total value of packed items?
  • 14.  Let’s add another parameter: w, which will represent the maximum weight for each subset of items  The subproblem then will be to compute V[k,w], i.e., to find an optimal solution for Sk = {items labeled 1, 2, .. k} in a knapsack of size w
  • 15.  The subproblem will then be to compute V[k,w], i.e., to find an optimal solution for Sk = {items labeled 1, 2, .. k} in a knapsack of size w  Assuming knowing V[i, j], where i=0,1, 2, … k-1, j=0,1,2, …w, how to derive V[k,w]?
  • 16. It means, that the best subset of Sk that has total weight w is: 1) the best subset of Sk-1 that has total weight ≤ w, or 2) the best subset of Sk-1 that has total weight ≤ w-wk plus the item k    +−−− >− = else}],1[],,1[max{ if],1[ ],[ kk k bwwkVwkV wwwkV wkV Recursive formula for subproblems:
  • 17.  The best subset of Sk that has the total weight ≤ w, either contains item k or not.  First case: wk>w. Item k can’t be part of the solution, since if it was, the total weight would be > w, which is unacceptable.  Second case: wk ≤ w. Then the item k can be in the solution, and we choose the case with greater value.    +−−− >− = else}],1[],,1[max{ if],1[ ],[ kk k bwwkVwkV wwwkV wkV
  • 18. for w = 0 to W V[0,w] = 0 for i = 1 to n V[i,0] = 0 for i = 1 to n for w = 0 to W if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w
  • 19. for w = 0 to W V[0,w] = 0 for i = 1 to n V[i,0] = 0 for i = 1 to n for w = 0 to W < the rest of the code > What is the running time of this algorithm? O(W) O(W) Repeat n times O(n*W) Remember that the brute-force algorithm takes O(2n )
  • 20. Let’s run our algorithm on the following data: n = 4 (# of elements) W = 5 (max weight) Elements (weight, benefit): (2,3), (3,4), (4,5), (5,6)
  • 21. for w = 0 to W V[0,w] = 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW
  • 22. for i = 1 to n V[i,0] = 0 0 0 0 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW
  • 23. if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w 0 Items: 1: (2,3) 2: (3,4) 3: (4,5) 4: (5,6) 0 i=1 bi=3 wi=2 w=1 w-wi =-1 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW 0 0 0
  • 24. Items: 1: (2,3) 2: (3,4) 3: (4,5) 4: (5,6) 300 0 0 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW i=1 bi=3 wi=2 w=4 w-wi =2 if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w 3 3
  • 25. Items: 1: (2,3) 2: (3,4) 3: (4,5) 4: (5,6) 300 0 0 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW i=1 bi=3 wi=2 w=5 w-wi =3 if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w 3 3 3
  • 26. Items: 1: (2,3) 2: (3,4) 3: (4,5) 4: (5,6) 00 0 0 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW i=2 bi=4 wi=3 w=2 w-wi =-1 3 3 3 3 3 if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w 0
  • 27. Items: 1: (2,3) 2: (3,4) 3: (4,5) 4: (5,6) 00 0 0 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW i=2 bi=4 wi=3 w=3 w-wi =0 3 3 3 3 0 if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w 43
  • 28. Items: 1: (2,3) 2: (3,4) 3: (4,5) 4: (5,6) 00 0 0 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW i=3 bi=5 wi=4 w= 1..3 3 3 3 3 0 3 4 4 if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w 7 3 40
  • 29. Items: 1: (2,3) 2: (3,4) 3: (4,5) 4: (5,6) 00 0 0 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW i=4 bi=6 wi=5 w= 1..4 3 3 3 3 0 3 4 4 if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w 7 3 40 70 3 4 5 5
  • 30. Items: 1: (2,3) 2: (3,4) 3: (4,5) 4: (5,6) 00 0 0 0 0 0 0 0 000 1 2 3 4 50 1 2 3 4 iW i=4 bi=6 wi=5 w= 5 w- wi=0 3 3 3 3 0 3 4 4 7 0 3 4 if wi <= w // item i can be part of the solution if bi + V[i-1,w-wi] > V[i-1,w] V[i,w] = bi + V[i-1,w- wi] else V[i,w] = V[i-1,w] else V[i,w] = V[i-1,w] // wi > w 5 7 7 0 3 4 5
  • 31.  This algorithm only finds the max possible value that can be carried in the knapsack ◦ i.e., the value in V[n,W]  To know the items that make this maximum value, an addition to this algorithm is necessary
  • 32.  All of the information we need is in the table.  V[n,W] is the maximal value of items that can be placed in the Knapsack.  Let i=n and k=W if V[i,k] ≠ V[i−1,k] then mark the ith item as in the knapsack i = i−1, k = k-wi else i = i−1 // Assume the ith item is not in the knapsack // Could it be in the optimally packed knapsack?
  • 33.  Goal: ◦ Solve only subproblems that are necessary and solve it only once  Memorization is another way to deal with overlapping subproblems in dynamic programming  With memorization, we implement the algorithm recursively: ◦ If we encounter a new subproblem, we compute and store the solution. ◦ If we encounter a subproblem we have seen, we look up the answer  Most useful when the algorithm is easiest to implement recursively ◦ Especially if we do not need solutions to all subproblems.
  • 34. for i = 1 to n for w = 1 to W V[i,w] = -1 for w = 0 to W V[0,w] = 0 for i = 1 to n V[i,0] = 0 MFKnapsack(i, w) if V[i,w] < 0 if w < wi value = MFKnapsack(i-1, w) else value = max(MFKnapsack(i-1, w), bi + MFKnapsack(i-1, w-wi)) V[i,w] = value return V[i,w]
  • 35.  Dynamic programming is a useful technique of solving certain kind of problems  When the solution can be recursively described in terms of partial solutions, we can store these partial solutions and re-use them as necessary (memorization)  Running time of dynamic programming algorithm vs. naïve algorithm: ◦ 0-1 Knapsack problem: O(W*n) vs. O(2n )
  • 36. Design and Analysis of Algorithms - Chapter 8 36