Lecture 6 - Dynamic Programming
Lecture 6 - Dynamic Programming
Dynamic Programming
Md Mehrab Hossain Opi
Introduction 2
• Like the divide-and-conquer method, DP solves problems by combining
the solutions to subproblems.
• Then what’s the difference?
• D&C partitioned a problem into disjoint subproblems.
• Solve the subproblems recursively, and then combine their solutions to
solve the original problem.
• Merge Sort / Quick Sort.
1 2 3 4
1 5 8 9
• Special case (no cuts): First piece is the full rod sizeand revenue ;
remainder is zero with revenue
• This approach simplifies the solution to include only one related
subproblem (the remainder) instead of two.
return Memoized-
Aux(p,n,r)
Memoized-Aux(p, n, r)
if //already have a solution
return r[n]
if n==0 then q = 0
else{
q =
for to n // is the position of first cut
q = max{q,p[i]+Memoized-Aux(p, n-i, r)
r[n] = q // remember the solution value for length n
return q
CSE 2201: Algorithm Analysis and Design December 21, 2024
Rod Cutting Problem – Bottom-Up Approach 22
• Relies on a natural order of subproblems, where each subproblem
depends only on smaller ones.
• Solve subproblems in ascending order of size, starting with the
smallest.
• Store each solution when it is first solved.
• For each subproblem, all smaller prerequisite subproblems are already
solved and stored.
• Ensures each subproblem is solved only once, with prerequisites ready
when needed.
Bottom-Up-Cut-Rod(p, n, r)
let r[0:n] be a new array // will remember solution values
in r.
r[0] = 0
for j = 1 to n // for increasing rod length j
q =
for to j // i is the position of the first cut
q = max{q, p[i]+r[j-i]}
r[j] = q // remember the solution for length j
return r[n]
• Additionally, we will maintain array s, such that stores the index k that
gives the minimum cost for splitting
• This array will be used to reconstruct the solution.
• If you look closely there are only unique subproblem for choice of
and .
• Overlapping subproblems make DP suitable for this problem.
• Let’s see the bottom-up approach.
Thank You.