Skip to content

Commit 52ed1dc

Browse files
Added code for unbounded knapsack in C++ (#1428)
* Added code for unbounded knapsack in C++ * Added unbounded knapsack code * Moved time complexity below test cases * Update unbounded_knapsack.cpp Co-authored-by: Tarun Yadav <[email protected]>
1 parent f397774 commit 52ed1dc

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

Algorithm/DP/readme.md

+1
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,5 @@ be avoided by constructinng a temporary array dp[] and memoizing the computed va
4646
- Painting Fence Algorithm ----> [Python](/Code/Python/PaintFenceAlgo.py) | [Java](/Code/Java/Paint_fence_algo.java)
4747
- Shortest Common Supersequence ---->[C++](/Code/C++/print_shortest_supersequence.cpp)
4848
- Word Wrap Problem ----> [C++](/Code/C++/word_wrap.cpp)
49+
- Unbounded Knapsack ----> [C++](/Code/C++/unbounded_knapsack.cpp)
4950
- Painting Fence algorithm ----> [C++](/Code/C++/paint_fence.cpp)

Code/C++/unbounded_knapsack.cpp

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/* Unbounded Knapsack
2+
Given: a knapsack of weight W and n number of items
3+
Task: find the maximum value of items that can be packed into the knapsack if unlimited number of each item can be included
4+
*/
5+
6+
#include <bits/stdc++.h>
7+
using namespace std;
8+
int Knapsack(int w[], int val[], int n, int W)
9+
{
10+
//Initialization of the array
11+
int dp[n + 1][W + 1];
12+
13+
//Base conditions
14+
for (int i = 0; i < n + 1; i++)
15+
{
16+
for (int j = 0; j < W + 1; j++)
17+
{
18+
if (i == 0 || j == 0)
19+
dp[i][j] = 0;
20+
}
21+
}
22+
23+
for (int i = 1; i < n + 1; i++)
24+
{
25+
for (int j = 1; j < W + 1; j++)
26+
{
27+
if (w[i - 1] <= j)
28+
dp[i][j] = max((val[i - 1] + dp[i][j - w[i - 1]]), dp[i - 1][j]);
29+
else
30+
dp[i][j] = dp[i - 1][j];
31+
}
32+
}
33+
return dp[n][W];
34+
}
35+
int main()
36+
{
37+
int n;
38+
cin >> n;
39+
int w[n], val[n];
40+
for (int i = 0; i < n; i++)
41+
cin >> w[i] >> val[i];
42+
int W;
43+
cin >> W;
44+
cout << Knapsack(w, val, n, W);
45+
}
46+
47+
/*
48+
TEST CASE 1:
49+
50+
INPUT:
51+
5
52+
10 200
53+
5 60
54+
3 90
55+
2 10
56+
1 6
57+
20
58+
59+
OUTPUT:
60+
552
61+
62+
TEST CASE 2:
63+
64+
INPUT:
65+
2
66+
10 100
67+
2 40
68+
15
69+
70+
OUTPUT:
71+
280
72+
73+
Time Complexity: O(N*W)
74+
Space Complexity: O(N*W)
75+
*/

0 commit comments

Comments
 (0)