SlideShare a Scribd company logo
1 of 15
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

Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityBhavin Darji
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problemsJyotsna Suryadevara
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
Fractional Knapsack Problem
Fractional Knapsack ProblemFractional Knapsack Problem
Fractional Knapsack Problemharsh kothari
 
Knapsack problem using greedy approach
Knapsack problem using greedy approachKnapsack problem using greedy approach
Knapsack problem using greedy approachpadmeshagrekar
 
01 Knapsack using Dynamic Programming
01 Knapsack using Dynamic Programming01 Knapsack using Dynamic Programming
01 Knapsack using Dynamic ProgrammingFenil Shah
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithmSrikrishnan Suresh
 
0/1 knapsack
0/1 knapsack0/1 knapsack
0/1 knapsackAmin Omi
 
Algorithm Using Divide And Conquer
Algorithm Using Divide And ConquerAlgorithm Using Divide And Conquer
Algorithm Using Divide And ConquerUrviBhalani2
 
Dynamic Programming-Knapsack Problem
Dynamic Programming-Knapsack ProblemDynamic Programming-Knapsack Problem
Dynamic Programming-Knapsack ProblemAmrita Yadav
 

What's hot (20)

Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of Optimality
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problems
 
Knapsack
KnapsackKnapsack
Knapsack
 
Greedy method by Dr. B. J. Mohite
Greedy method by Dr. B. J. MohiteGreedy method by Dr. B. J. Mohite
Greedy method by Dr. B. J. Mohite
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Fractional Knapsack Problem
Fractional Knapsack ProblemFractional Knapsack Problem
Fractional Knapsack Problem
 
Knapsack Problem
Knapsack ProblemKnapsack Problem
Knapsack Problem
 
Knapsack problem using greedy approach
Knapsack problem using greedy approachKnapsack problem using greedy approach
Knapsack problem using greedy approach
 
01 Knapsack using Dynamic Programming
01 Knapsack using Dynamic Programming01 Knapsack using Dynamic Programming
01 Knapsack using Dynamic Programming
 
Greedy method
Greedy methodGreedy method
Greedy method
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Convex hull
Convex hullConvex hull
Convex hull
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
 
5.1 greedy
5.1 greedy5.1 greedy
5.1 greedy
 
0/1 knapsack
0/1 knapsack0/1 knapsack
0/1 knapsack
 
Algorithm Using Divide And Conquer
Algorithm Using Divide And ConquerAlgorithm Using Divide And Conquer
Algorithm Using Divide And Conquer
 
Dynamic Programming-Knapsack Problem
Dynamic Programming-Knapsack ProblemDynamic Programming-Knapsack Problem
Dynamic Programming-Knapsack Problem
 
N queens using backtracking
N queens using backtrackingN queens using backtracking
N queens using backtracking
 

Similar to Maximum Value Knapsack Problem Solved with Dynamic Programming

Knapsack Dynamic
Knapsack DynamicKnapsack Dynamic
Knapsack DynamicParas Patel
 
knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandboundhodcsencet
 
Knapsack problem and Memory Function
Knapsack problem and Memory FunctionKnapsack problem and Memory Function
Knapsack problem and Memory FunctionBarani Tharan
 
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEMMrunal Patil
 
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.pptQurbanAli72
 
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 ProgrammingEditor IJCTER
 
Unit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxUnit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxMaryJacob24
 
Unit 3 - Greedy Method
Unit 3  - Greedy MethodUnit 3  - Greedy Method
Unit 3 - Greedy MethodMaryJacob24
 
Unit 3 greedy method
Unit 3  greedy methodUnit 3  greedy method
Unit 3 greedy methodMaryJacob24
 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamicchidabdu
 
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.pptdakccse
 
Ms nikita greedy agorithm
Ms nikita greedy agorithmMs nikita greedy agorithm
Ms nikita greedy agorithmNikitagupta123
 
Optimization problems
Optimization problemsOptimization problems
Optimization problemsRuchika Sinha
 
Presentation of knapsack
Presentation of knapsackPresentation of knapsack
Presentation of knapsackGaurav Dubey
 

Similar to Maximum Value Knapsack Problem Solved with Dynamic Programming (20)

Knapsack Dynamic
Knapsack DynamicKnapsack Dynamic
Knapsack Dynamic
 
knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandbound
 
Knapsack problem and Memory Function
Knapsack problem and Memory FunctionKnapsack problem and Memory Function
Knapsack problem and Memory Function
 
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
 
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 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
 
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
 
Optimization problems
Optimization problemsOptimization problems
Optimization problems
 
Presentation of knapsack
Presentation of knapsackPresentation of knapsack
Presentation of knapsack
 

More from Abhishek Singh

Knights tour on chessboard using backtracking
Knights tour on chessboard using backtrackingKnights tour on chessboard using backtracking
Knights tour on chessboard using backtrackingAbhishek Singh
 
RABIN KARP ALGORITHM STRING MATCHING
RABIN KARP ALGORITHM STRING MATCHINGRABIN KARP ALGORITHM STRING MATCHING
RABIN KARP ALGORITHM STRING MATCHINGAbhishek Singh
 
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 boundAbhishek Singh
 
kmp_algorithm (string matching)
kmp_algorithm (string matching)kmp_algorithm (string matching)
kmp_algorithm (string matching)Abhishek Singh
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using BacktrackingAbhishek 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

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 

Recently uploaded (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 

Maximum Value Knapsack Problem Solved with Dynamic Programming

  • 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