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