12 23ec60 Data Structures and Algorithms Kir Dynammic Programming
12 23ec60 Data Structures and Algorithms Kir Dynammic Programming
DATA STRUCTURES
AND
ALGORITHMS
DYNAMMIC PROGRAMMING
Prepared by,
Mrs. K. Iyshwarya Ratthi
Assistant Professor,
Department of ECE
Explanation:
If you want to solve a complex problem optimally using dynamic
programming, you break it down into smaller overlapping
subproblems.
The principle of optimality ensures that:
• Solving each subproblem optimally is sufficient.
• The combination of these optimal subproblem solutions will give
the optimal solution to the overall problem.
Examples of dynamic programming:
1. Knapsack problem
2. Longest common subsequence
0/1 Knapsack Problem
• Starting from the last object, we have a profit of 6 from object 4. We can include
object 4 and subtract the profit of object 4 from the maximum profit. So, 8-6 = 2 is
the profit remaining. We have to now check by including which object we can get a
profit of 2.
• Check for 2 in the above row (i=3). Is there a 2? Yes, it is. But is it solely achieved
from object 3? No. Why because there is one more 2 in the above row as well (i=2).
It can be understood that it is obtained by including another object, not 2. Now
check in the above row for 2. Yes, it exists. It is achieved from object 2. Hence,
include object 2. The remaining profit is 2-2=0. So, we got our solution.
n: Number of items.
W: Maximum weight the knapsack can hold.
w[10]: Array to store weights of items.
v[10]: Array to store values/profits of items.
V[10][10]: 2D array (DP table) to store maximum profit at each subproblem.
x[10]: Array to mark whether an item is included in the optimal solution.
void Knapsack()
{
int i, j; Loops through each item (i) and weight capacity (j).
for (i = 0; i <= n; i++)
{
for (j = 0; j <= W; j++)
{
if (i == 0 || j == 0) Base case: If no items or weight capacity is 0, profit is 0.
V[i][j] = 0;
else if (j < w[i])
V[i][j] = V[i - 1][j];
else
V[i][j] = max(V[i - 1][j], V[i - 1][j - w[i]] + v[i]);
while (i != 0 && j != 0) If the value differs from the one above, it means the item
{ was included.
if (V[i][j] != V[i - 1][j])
{ Mark it as included and reduce the capacity.
x[i] = 1;
j = j - w[i];
}
i--;
}
}
int main()
{
int i;
printf("object\tweight\tprofit\n");
for (i = 1; i <= n; i++)
if (x[i] == 1)
printf("%d\t%d\t%d\n", i, w[i], v[i]);
return 0;
} Print selected items and their weights/profits.
Print the maximum profit from the DP table and exit the
program.
Dynamic programming table V[i][j]
Longest Common Subsequence
• Subsequence:
• BDFH is a subsequence of ABCDEFGH
• If X and Y are sequences, a common subsequence
is a sequence which is a subsequence of both.
• BDFH is a common subsequence of ABCDEFGH
and of ABDFGHI
• A longest common subsequence…
• …is a common subsequence that is longest.
• The longest common subsequence of ABCDEFGH and
ABDFGHI is ABDFGH.