SlideShare a Scribd company logo
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
Dynamic Programming
Dynamic Programming (DP) is an algorithmic technique for solving an optimization problem by breaking it down into
simpler subproblems and utilizing the fact that the optimal solution to the overall problem depends upon the optimal
solution to its subproblems.
Characteristics of DP
1) Overlapping Subproblems: Subproblems are smaller versions of the original problem. Any problem has
overlapping sub-problems if finding its solution involves solving the same subproblem multiple times.
2) Optimal Substructure Property: Any problem has optimal substructure property if its overall optimal solution
can be constructed from the optimal solutions of its subproblems.
For Fibonacci numbers,
Recursive formula: 𝑓𝑖𝑏(𝑛) = {
0; 𝑛 = 0
1; 𝑛 = 1
𝑓𝑖𝑏(𝑛 − 1) + 𝑓𝑖𝑏(𝑛 − 2); 𝑛 > 1
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
DP Methods
1) Top-down with Memorization: In this approach, we try to solve the bigger problem by recursively finding the
solution to smaller sub-problems. Whenever we solve a sub-problem, we cache its result so that we don’t end
up solving it repeatedly if it’s called multiple times. Instead, we can just return the saved result. This technique
of storing the results of already solved subproblems is called Memorization.
Recursive Implementation Top-down with Memorization
int fib(int term){
if(term==0){
return 0; ///base condition 1
}
else if(term==1){
return 1; ///base condition 2
}
else{
///recursive subproblems
int myresult=fib(term-1)
+fib(term-2);
return myresult;
}
}
int cache[100]={0};
int memfib(int term){
if(term==0){
return 0; ///base condition 1
}
else if(term==1){
return 1; ///base condition 1
}
else{
///checking the cache memory
if(cache[term]!=0){
///found
return cache[term];
}
else{
///not found
cache[term]=memfib(term-1)
+memfib(term-2);
return cache[term];
}
}
}
2) Bottom-up with Tabulation: Tabulation is the opposite of the top-down approach and avoids recursion. In this
approach, we solve the problem “bottom-up” (i.e. by solving all the related sub-problems first). This is typically
done by filling up an n-dimensional table. Based on the results in the table, the solution to the top/original
problem is then computed.
Recursive Implementation Bottom-up with Tabulation
int fib(int term){
if(term==0){
return 0; ///base condition 1
}
else if(term==1){
return 1; ///base condition 2
}
else{
///recursive subproblems
int myresult=fib(term-1)
+fib(term-2);
return myresult;
}
}
int dptable[100];
int dpfib(int term){
dptable[0]=0; ///base condition 1
dptable[1]=1; ///base condition 2
///filling up the table
for(int t=2;t<=term;t++){
dptable[t]=dptable[t-1]+dptable[t-2];
}
return dptable[term];
}
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
Practice 1 – Staircase problem
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs
at a time. Count the number of ways, the person can reach the top.
Ref: https://www.geeksforgeeks.org/count-ways-reach-nth-stair/
Practice 2 – Tiling problem
Given a “2 x n” board and tiles of size “2 x 1”, count the number of ways to tile the given board using the 2 x 1 tiles. A tile
can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile.
Ref: https://www.geeksforgeeks.org/tiling-problem/
Practice 3 – Friends pairing problem
Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only
once. Find out the total number of ways in which friends can remain single or can be paired up.
Ref: https://www.geeksforgeeks.org/friends-pairing-problem/
Practice 4 – House thief
There are n houses build in a line, each of which contains some value in it. A thief is going to steal the maximal value of
these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two
neighbors left and right side. What is the maximum stolen value?
Ref: https://www.geeksforgeeks.org/find-maximum-possible-stolen-value-houses/
Practice 5 – Minimum jumps to reach end
Given an array of integers where each element represents the max number of steps that can be made forward from that
element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first
element). If an element is 0, they cannot move through that element. If the end isn’t reachable, return -1.
Ref: https://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-of-a-given-array/
Problem 6 – Catalan Number
Find out the nth
Catalan number.
First few Catalan numbers for n = 0, 1, 2, 3, 4, … are 1, 1, 2, 5, 14, 42, … etc.
Recursive formula: 𝐶(𝑛) = {
1; 𝑛 = 0
∑ 𝐶(𝑖) ∗ 𝐶(𝑛 − 1 − 𝑖)
𝑛−1
𝑖=0
Ref: https://www.geeksforgeeks.org/program-nth-catalan-number/
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
Practice 7 – Binomial coefficient
Write a function that takes two parameters n, r and returns the value of Binomial Coefficient C(n, r) or, nCr.
Ref: https://www.geeksforgeeks.org/binomial-coefficient-dp-9/
Practice 8 – Permutation coefficient
Write a function that takes two parameters n, r and returns the value of nPr.
Ref: https://www.geeksforgeeks.org/permutation-coefficient/
Practice 9 – Subset sum
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to
given sum.
Ref: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/
Practice 10 – 0/1 Knapsack problem
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the
knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights
associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum
value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item,
either pick the complete item or don’t pick it (0-1 property).
Ref: https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
Practice 11 – Longest Common Subsequence
Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that
appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, ..
etc are subsequences of “abcdefg”.
Ref: https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/
Practice 12 – Edit Distance
Given two strings str1 and str2 and 3 operations (Insert, Replace, Delete) that can be performed on str1. Find minimum
number of edits (operations) required to convert ‘str1’ into ‘str2’. All of the above operations are of equal cost.
Ref: https://www.geeksforgeeks.org/edit-distance-dp-5/

More Related Content

Similar to DS & Algo 6 - Dynamic Programming

Perform brute force
Perform brute forcePerform brute force
Perform brute force
SHC
 
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
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
Raffi Khatchadourian
 
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
BinayakMukherjee4
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
yashodamb
 
Daa chapter4
Daa chapter4Daa chapter4
Daa chapter4
B.Kirron Reddi
 
Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
B.Kirron Reddi
 
Algorithms Design Patterns
Algorithms Design PatternsAlgorithms Design Patterns
Algorithms Design Patterns
Ashwin Shiv
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103Sure Interview
 
Analysis and design of algorithms part 4
Analysis and design of algorithms part 4Analysis and design of algorithms part 4
Analysis and design of algorithms part 4
Deepak John
 
Python recursion
Python recursionPython recursion
Python recursion
ToniyaP1
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programmingOye Tu
 
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Traian Rebedea
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Module 3_DAA (2).pptx
Module 3_DAA (2).pptxModule 3_DAA (2).pptx
Module 3_DAA (2).pptx
AnkitaVerma776806
 
Analysis and Design of Algorithms notes
Analysis and Design of Algorithms  notesAnalysis and Design of Algorithms  notes
Analysis and Design of Algorithms notes
Prof. Dr. K. Adisesha
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Melaku Bayih Demessie
 
Maxima & Minima for IIT JEE | askIITians
Maxima & Minima for IIT JEE | askIITiansMaxima & Minima for IIT JEE | askIITians
Maxima & Minima for IIT JEE | askIITians
askiitian
 

Similar to DS & Algo 6 - Dynamic Programming (20)

Perform brute force
Perform brute forcePerform brute force
Perform brute force
 
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
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
 
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
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
 
Daa chapter4
Daa chapter4Daa chapter4
Daa chapter4
 
Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
 
Algorithms Design Patterns
Algorithms Design PatternsAlgorithms Design Patterns
Algorithms Design Patterns
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
Analysis and design of algorithms part 4
Analysis and design of algorithms part 4Analysis and design of algorithms part 4
Analysis and design of algorithms part 4
 
Python recursion
Python recursionPython recursion
Python recursion
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Module 3_DAA (2).pptx
Module 3_DAA (2).pptxModule 3_DAA (2).pptx
Module 3_DAA (2).pptx
 
Analysis and Design of Algorithms notes
Analysis and Design of Algorithms  notesAnalysis and Design of Algorithms  notes
Analysis and Design of Algorithms notes
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Maxima & Minima for IIT JEE | askIITians
Maxima & Minima for IIT JEE | askIITiansMaxima & Minima for IIT JEE | askIITians
Maxima & Minima for IIT JEE | askIITians
 

More from Mohammad Imam Hossain

DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6
Mohammad Imam Hossain
 
DS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MSTDS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MST
Mohammad Imam Hossain
 
DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path Search
Mohammad Imam Hossain
 
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3
Mohammad Imam Hossain
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
Mohammad Imam Hossain
 
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2
Mohammad Imam Hossain
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
Mohammad Imam Hossain
 
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1
Mohammad Imam Hossain
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL Introduction
Mohammad Imam Hossain
 
DBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMSDBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMS
Mohammad Imam Hossain
 
DBMS 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
Mohammad Imam Hossain
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
Mohammad Imam Hossain
 
DBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship ModelDBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship Model
Mohammad Imam Hossain
 
DBMS 7 | Relational Query Language
DBMS 7 | Relational Query LanguageDBMS 7 | Relational Query Language
DBMS 7 | Relational Query Language
Mohammad Imam Hossain
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
Mohammad Imam Hossain
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
Mohammad Imam Hossain
 
TOC 10 | Turing Machine
TOC 10 | Turing MachineTOC 10 | Turing Machine
TOC 10 | Turing Machine
Mohammad Imam Hossain
 
TOC 9 | Pushdown Automata
TOC 9 | Pushdown AutomataTOC 9 | Pushdown Automata
TOC 9 | Pushdown Automata
Mohammad Imam Hossain
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity Check
Mohammad Imam Hossain
 
TOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal FormTOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal Form
Mohammad Imam Hossain
 

More from Mohammad Imam Hossain (20)

DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6
 
DS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MSTDS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MST
 
DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path Search
 
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
 
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL Introduction
 
DBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMSDBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMS
 
DBMS 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
 
DBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship ModelDBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship Model
 
DBMS 7 | Relational Query Language
DBMS 7 | Relational Query LanguageDBMS 7 | Relational Query Language
DBMS 7 | Relational Query Language
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
TOC 10 | Turing Machine
TOC 10 | Turing MachineTOC 10 | Turing Machine
TOC 10 | Turing Machine
 
TOC 9 | Pushdown Automata
TOC 9 | Pushdown AutomataTOC 9 | Pushdown Automata
TOC 9 | Pushdown Automata
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity Check
 
TOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal FormTOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal Form
 

Recently uploaded

CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 

Recently uploaded (20)

CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 

DS & Algo 6 - Dynamic Programming

  • 1. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com Dynamic Programming Dynamic Programming (DP) is an algorithmic technique for solving an optimization problem by breaking it down into simpler subproblems and utilizing the fact that the optimal solution to the overall problem depends upon the optimal solution to its subproblems. Characteristics of DP 1) Overlapping Subproblems: Subproblems are smaller versions of the original problem. Any problem has overlapping sub-problems if finding its solution involves solving the same subproblem multiple times. 2) Optimal Substructure Property: Any problem has optimal substructure property if its overall optimal solution can be constructed from the optimal solutions of its subproblems. For Fibonacci numbers, Recursive formula: 𝑓𝑖𝑏(𝑛) = { 0; 𝑛 = 0 1; 𝑛 = 1 𝑓𝑖𝑏(𝑛 − 1) + 𝑓𝑖𝑏(𝑛 − 2); 𝑛 > 1
  • 2. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com DP Methods 1) Top-down with Memorization: In this approach, we try to solve the bigger problem by recursively finding the solution to smaller sub-problems. Whenever we solve a sub-problem, we cache its result so that we don’t end up solving it repeatedly if it’s called multiple times. Instead, we can just return the saved result. This technique of storing the results of already solved subproblems is called Memorization. Recursive Implementation Top-down with Memorization int fib(int term){ if(term==0){ return 0; ///base condition 1 } else if(term==1){ return 1; ///base condition 2 } else{ ///recursive subproblems int myresult=fib(term-1) +fib(term-2); return myresult; } } int cache[100]={0}; int memfib(int term){ if(term==0){ return 0; ///base condition 1 } else if(term==1){ return 1; ///base condition 1 } else{ ///checking the cache memory if(cache[term]!=0){ ///found return cache[term]; } else{ ///not found cache[term]=memfib(term-1) +memfib(term-2); return cache[term]; } } } 2) Bottom-up with Tabulation: Tabulation is the opposite of the top-down approach and avoids recursion. In this approach, we solve the problem “bottom-up” (i.e. by solving all the related sub-problems first). This is typically done by filling up an n-dimensional table. Based on the results in the table, the solution to the top/original problem is then computed. Recursive Implementation Bottom-up with Tabulation int fib(int term){ if(term==0){ return 0; ///base condition 1 } else if(term==1){ return 1; ///base condition 2 } else{ ///recursive subproblems int myresult=fib(term-1) +fib(term-2); return myresult; } } int dptable[100]; int dpfib(int term){ dptable[0]=0; ///base condition 1 dptable[1]=1; ///base condition 2 ///filling up the table for(int t=2;t<=term;t++){ dptable[t]=dptable[t-1]+dptable[t-2]; } return dptable[term]; }
  • 3. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com Practice 1 – Staircase problem There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top. Ref: https://www.geeksforgeeks.org/count-ways-reach-nth-stair/ Practice 2 – Tiling problem Given a “2 x n” board and tiles of size “2 x 1”, count the number of ways to tile the given board using the 2 x 1 tiles. A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. Ref: https://www.geeksforgeeks.org/tiling-problem/ Practice 3 – Friends pairing problem Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. Ref: https://www.geeksforgeeks.org/friends-pairing-problem/ Practice 4 – House thief There are n houses build in a line, each of which contains some value in it. A thief is going to steal the maximal value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbors left and right side. What is the maximum stolen value? Ref: https://www.geeksforgeeks.org/find-maximum-possible-stolen-value-houses/ Practice 5 – Minimum jumps to reach end Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, they cannot move through that element. If the end isn’t reachable, return -1. Ref: https://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-of-a-given-array/ Problem 6 – Catalan Number Find out the nth Catalan number. First few Catalan numbers for n = 0, 1, 2, 3, 4, … are 1, 1, 2, 5, 14, 42, … etc. Recursive formula: 𝐶(𝑛) = { 1; 𝑛 = 0 ∑ 𝐶(𝑖) ∗ 𝐶(𝑛 − 1 − 𝑖) 𝑛−1 𝑖=0 Ref: https://www.geeksforgeeks.org/program-nth-catalan-number/
  • 4. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com Practice 7 – Binomial coefficient Write a function that takes two parameters n, r and returns the value of Binomial Coefficient C(n, r) or, nCr. Ref: https://www.geeksforgeeks.org/binomial-coefficient-dp-9/ Practice 8 – Permutation coefficient Write a function that takes two parameters n, r and returns the value of nPr. Ref: https://www.geeksforgeeks.org/permutation-coefficient/ Practice 9 – Subset sum Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. Ref: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/ Practice 10 – 0/1 Knapsack problem Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property). Ref: https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/ Practice 11 – Longest Common Subsequence Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. Ref: https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/ Practice 12 – Edit Distance Given two strings str1 and str2 and 3 operations (Insert, Replace, Delete) that can be performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’. All of the above operations are of equal cost. Ref: https://www.geeksforgeeks.org/edit-distance-dp-5/