SlideShare a Scribd company logo
Presented By :- Abhishek Kumar Singh
2015UGCS018
B-Tech ( 6th Semester)
NIT Jamshedpur
0-1 Knapsack problem
Overview
• 0-1 knapsack , its types and recursive
implementation
• Optimization of recursive solution using
Memorization
0-1 Knapsack problem
 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?
Knapsack problem
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
0-1 Knapsack problem: Naïve
recursive approach
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)
Approach
 To consider all subsets of items, there
can be two cases for every item:
(1) the item is included in the optimal
subset,
(2) not included in the optimal set.
Approach
Therefore, the maximum value that can be
obtained from n items is max of following two
values.
1) Maximum value obtained by n-1 items and
W weight (excluding nth item).
2) Value of nth item plus maximum value
obtained by n-1 items and W minus weight of
the nth item (including nth item).
 If weight of nth item is greater than W, then
the nth item cannot be included and case 1 is
the only possibility.
Following is knapsack function
 int knapSack(int W, int wt[], int val[], int n)
 {
 // Base Case
 if (n == 0 || W == 0)
 return 0;
 // If weight of the nth item is more than Knapsack capacity W, then
 // this item cannot be included in the optimal solution
 if (wt[n-1] > W)
 return knapSack(W, wt, val, n-1);

 // Return the maximum of two cases:
 // (1) nth item included
 // (2) not included
 else return max( val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
 knapSack(W, wt, val, n-1) );

 }
STATE SPACE TREE
In the following recursion tree, K() refers to knapSack().
The two parameters indicated in the following recursion
tree are n and W. The recursion tree is for following sample
inputs. wt[] = {1, 1, 1}, W = 2, val[] = {10, 20, 30}
Problem in the previous
approach
It should be noted that the above
function computes the same
subproblems again and again. See the
above recursion tree, K(1, 1) is being
evaluated twice. Time complexity of
this naive recursive solution is
exponential (2^n).
To overcome this problem we can use
the dynamic
programming technique, which
basically involved storing the solutions
Recursive Top-Down Dynamic programming
approach memorization
 Top-down dynamic programming
means that we’ll use same recursive
algorithm to solve the problem, but instead
of simply returning the computed values
from our function we’ll first store it in an
auxiliary table. Then every time we call the
recursion we first check the table to see if
the solution was computed already. If it
was we use it, else we compute and store
it for future use.
int matrix[100][100] = {0};
int knapsack( int index, int size, int weights[], int values[] )
{
int take,dontTake;
take = dontTake = 0;
if (matrix[index][size]!=0) //checking whether the subproblem is
return matrix[index][size]; // already calculated or not
if (index==0)  // If the given subproblem is at leave node
{ if (weights[0]<=size)
{ matrix[index][size] = values[0];
return values[0]; }
else
{ matrix[index][size] = 0;
return 0; }
}
if (weights[index]<=size)
take = values[index] + knapsack(index-1, size-weights[index], weights,
values);
dontTake = knapsack(index-1, size, weights, values);
matrix[index][size] = max (take, dontTake);
return matrix[index][size];
Time Complexity
 The time complexity of the previous algorithm is
O(w*n) where ‘w’ is the maximum weight of the
knapsack and ‘n’ is the no. of elements .
 In the previous algorithm what we are using is
called Memorization.
 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
Advantages & Disadvantages
Advantage:
 It is used to find all the existing solution if
there exist for any problem.
 It is used for the problems where path
through which the solution is achieved is
important rather than the solution itself.
classic example of this is N-Queen
problem or Knight problem.
Disadvantage:
 Multiple function calls are expensive
 Requires large amount of space as the
each function state needs to be stored on
THANK YOU

More Related Content

What's hot

Knapsack problem dynamicprogramming
Knapsack problem dynamicprogrammingKnapsack problem dynamicprogramming
Knapsack problem dynamicprogramming
rowntu
 

What's hot (20)

Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and bound
 
04 brute force
04 brute force04 brute force
04 brute force
 
0/1 knapsack
0/1 knapsack0/1 knapsack
0/1 knapsack
 
Knapsack Problem
Knapsack ProblemKnapsack Problem
Knapsack Problem
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
 
Knapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmKnapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithm
 
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycleBacktracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
 
Maximum sum subarray
Maximum sum subarrayMaximum sum subarray
Maximum sum subarray
 
Knapsack problem dynamicprogramming
Knapsack problem dynamicprogrammingKnapsack problem dynamicprogramming
Knapsack problem dynamicprogramming
 
Data Structure and Algorithm - Divide and Conquer
Data Structure and Algorithm - Divide and ConquerData Structure and Algorithm - Divide and Conquer
Data Structure and Algorithm - Divide and Conquer
 
Fractional Knapsack Problem
Fractional Knapsack ProblemFractional Knapsack Problem
Fractional Knapsack Problem
 
8 queen problem
8 queen problem8 queen problem
8 queen problem
 
Knapsack problem using dynamic programming
Knapsack problem using dynamic programmingKnapsack problem using dynamic programming
Knapsack problem using dynamic programming
 
Max net
Max netMax net
Max net
 
Greedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack ProblemGreedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack Problem
 
Division algorithm
Division algorithmDivision algorithm
Division algorithm
 
Tsp branch and-bound
Tsp branch and-boundTsp branch and-bound
Tsp branch and-bound
 
Greedy Algorithms WITH Activity Selection Problem.ppt
Greedy Algorithms WITH Activity Selection Problem.pptGreedy Algorithms WITH Activity Selection Problem.ppt
Greedy Algorithms WITH Activity Selection Problem.ppt
 
knapsack problem
knapsack problemknapsack problem
knapsack problem
 
0-1 KNAPSACK PROBLEM
0-1 KNAPSACK PROBLEM0-1 KNAPSACK PROBLEM
0-1 KNAPSACK PROBLEM
 

Similar to 0 1 knapsack using naive recursive approach and top-down dynamic programming approach

knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandbound
hodcsencet
 
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
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
rupali_2bonde
 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamic
chidabdu
 
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
dakccse
 

Similar to 0 1 knapsack using naive recursive approach and top-down dynamic programming approach (20)

Knapsack Dynamic
Knapsack DynamicKnapsack Dynamic
Knapsack Dynamic
 
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
 
knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandbound
 
Knapsack problem and Memory Function
Knapsack problem and Memory FunctionKnapsack problem and Memory Function
Knapsack problem and Memory Function
 
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
 
A Survey- Knapsack Problem Using Dynamic Programming
A Survey- Knapsack Problem Using Dynamic ProgrammingA Survey- Knapsack Problem Using Dynamic Programming
A Survey- Knapsack Problem Using Dynamic Programming
 
Knapsack problem using greedy approach
Knapsack problem using greedy approachKnapsack problem using greedy approach
Knapsack problem using greedy approach
 
Knapsack dp
Knapsack dpKnapsack dp
Knapsack dp
 
knapsack.pptx
knapsack.pptxknapsack.pptx
knapsack.pptx
 
Module 3_DAA (2).pptx
Module 3_DAA (2).pptxModule 3_DAA (2).pptx
Module 3_DAA (2).pptx
 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy Method
 
Unit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxUnit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptx
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Unit 3 greedy method
Unit 3  greedy methodUnit 3  greedy method
Unit 3 greedy method
 
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
 
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
 
Ms nikita greedy agorithm
Ms nikita greedy agorithmMs nikita greedy agorithm
Ms nikita greedy agorithm
 

More from Abhishek Singh

More from Abhishek Singh (7)

Knights tour on chessboard using backtracking
Knights tour on chessboard using backtrackingKnights tour on chessboard using backtracking
Knights tour on chessboard using backtracking
 
RABIN KARP ALGORITHM STRING MATCHING
RABIN KARP ALGORITHM STRING MATCHINGRABIN KARP ALGORITHM STRING MATCHING
RABIN KARP ALGORITHM STRING MATCHING
 
Naive string matching
Naive string matchingNaive string matching
Naive string matching
 
15 puzzle problem using branch and bound
15 puzzle problem using branch and bound15 puzzle problem using branch and bound
15 puzzle problem using branch and bound
 
kmp_algorithm (string matching)
kmp_algorithm (string matching)kmp_algorithm (string matching)
kmp_algorithm (string matching)
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using Backtracking
 
Sudoku
SudokuSudoku
Sudoku
 

Recently uploaded

Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
Avinash Rai
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
YibeltalNibretu
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 

0 1 knapsack using naive recursive approach and top-down dynamic programming approach

  • 1. Presented By :- Abhishek Kumar Singh 2015UGCS018 B-Tech ( 6th Semester) NIT Jamshedpur 0-1 Knapsack problem
  • 2. Overview • 0-1 knapsack , its types and recursive implementation • Optimization of recursive solution using Memorization
  • 3. 0-1 Knapsack problem  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?
  • 4. Knapsack problem 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
  • 5. 0-1 Knapsack problem: Naïve recursive approach 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)
  • 6. Approach  To consider all subsets of items, there can be two cases for every item: (1) the item is included in the optimal subset, (2) not included in the optimal set.
  • 7. Approach Therefore, the maximum value that can be obtained from n items is max of following two values. 1) Maximum value obtained by n-1 items and W weight (excluding nth item). 2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nth item (including nth item).  If weight of nth item is greater than W, then the nth item cannot be included and case 1 is the only possibility.
  • 8. Following is knapsack function  int knapSack(int W, int wt[], int val[], int n)  {  // Base Case  if (n == 0 || W == 0)  return 0;  // If weight of the nth item is more than Knapsack capacity W, then  // this item cannot be included in the optimal solution  if (wt[n-1] > W)  return knapSack(W, wt, val, n-1);   // Return the maximum of two cases:  // (1) nth item included  // (2) not included  else return max( val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),  knapSack(W, wt, val, n-1) );   }
  • 9. STATE SPACE TREE In the following recursion tree, K() refers to knapSack(). The two parameters indicated in the following recursion tree are n and W. The recursion tree is for following sample inputs. wt[] = {1, 1, 1}, W = 2, val[] = {10, 20, 30}
  • 10. Problem in the previous approach It should be noted that the above function computes the same subproblems again and again. See the above recursion tree, K(1, 1) is being evaluated twice. Time complexity of this naive recursive solution is exponential (2^n). To overcome this problem we can use the dynamic programming technique, which basically involved storing the solutions
  • 11. Recursive Top-Down Dynamic programming approach memorization  Top-down dynamic programming means that we’ll use same recursive algorithm to solve the problem, but instead of simply returning the computed values from our function we’ll first store it in an auxiliary table. Then every time we call the recursion we first check the table to see if the solution was computed already. If it was we use it, else we compute and store it for future use.
  • 12. int matrix[100][100] = {0}; int knapsack( int index, int size, int weights[], int values[] ) { int take,dontTake; take = dontTake = 0; if (matrix[index][size]!=0) //checking whether the subproblem is return matrix[index][size]; // already calculated or not if (index==0)  // If the given subproblem is at leave node { if (weights[0]<=size) { matrix[index][size] = values[0]; return values[0]; } else { matrix[index][size] = 0; return 0; } } if (weights[index]<=size) take = values[index] + knapsack(index-1, size-weights[index], weights, values); dontTake = knapsack(index-1, size, weights, values); matrix[index][size] = max (take, dontTake); return matrix[index][size];
  • 13. Time Complexity  The time complexity of the previous algorithm is O(w*n) where ‘w’ is the maximum weight of the knapsack and ‘n’ is the no. of elements .  In the previous algorithm what we are using is called Memorization.  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
  • 14. Advantages & Disadvantages Advantage:  It is used to find all the existing solution if there exist for any problem.  It is used for the problems where path through which the solution is achieved is important rather than the solution itself. classic example of this is N-Queen problem or Knight problem. Disadvantage:  Multiple function calls are expensive  Requires large amount of space as the each function state needs to be stored on