Aoa Exp 7 40
Aoa Exp 7 40
07
Theory:
We are given N items where each item has some weight and profit associated with it.
We are also given a bag with capacity W, [i.e., the bag can hold at most W weight in it].
The target is to put the items into the bag such that the sum of profits associated with
them is the maximum possible. Initialize the solution matrix same as the input graph
matrix as a first step.
The constraint here is we can either put an item completely into the bag or cannot put it at
all [It is not possible to put a part of an item into the bag].
Algorithm:
Algorithm Knapsack_01(W, P, M, n):
For i from 1 to n:
For j from 1 to M:
diff = j - W[i - 1]
If diff >= 0:
Else:
j=M
x[i - 1] = 1
j = j - W[i - 1]
Experiment No. 07
If V[n][M] == 0:
For i from 0 to n - 1:
If x[i] = 1:
Return V[n][M], x
Begin:
Read n
Read W (weights)
Read P (profits)
Program:
#include <iostream>
#include <vector>
#include <algorithm>
// If no solution exists
if (V[n][M] == 0) {
cout << "Optimal solution does not exist." << endl;
return {0, {}};
Experiment No. 07
int main()
{ int n;
cout << "Enter number of items: ";
cin >> n;
int M;
cout << "Enter maximum weight capacity of knapsack: ";
cin >> M;
if (max_profit > 0) {
cout << "Maximum Profit: " << max_profit << endl;
cout << "Items Selected (1 means included, 0 means not included): ";
for (int item : items_selected) {
cout << item << " ";
}
cout << endl;
}
return 0;
}
Experiment No. 07
Output:
Experiment No. 07
Time Complexity:
The 0/1 Knapsack problem using Dynamic Programming has a time complexity of O(n ×
M), where:
We construct a DP table of size (n+1) × (M+1), and each entry in the table is computed in
constant time O(1). Thus, the overall complexity is O(n × M).
Space Complexity:
The space complexity is O(n × M) because we store a 2D DP table of size (n+1) × (M+1).
However, since the current state only depends on the previous row, the space can be
optimized to O(M) by using a 1D array instead of a full table.