-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack_problem_Unbounded_DP.cpp
More file actions
49 lines (40 loc) · 975 Bytes
/
Copy pathKnapsack_problem_Unbounded_DP.cpp
File metadata and controls
49 lines (40 loc) · 975 Bytes
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
#include <bits/stdc++.h>
using namespace std;
/*
Time Complexity : O((W+1)*N)
Space Complexity: O(W+1).
*/
int UKS(int W[], int P[], int wt, int n)
{
//initializing the array with 0.
int dp[wt+1] = {0};
for(int currentWt=0 ; currentWt<=wt ; currentWt++)
{
//Traversing the weight array
for(int i=0 ; i<n ; i++)
{
//accommodation case
if(W[i] <= currentWt)
dp[currentWt] = max(dp[currentWt] , dp[currentWt-W[i]] + P[i]);
}
}
return dp[wt];
}
int main()
{
int n;
cout<<"Enter size of the weight/profit array : ";
cin>>n;
int wt;
cout<<"Enter weight of the carry-bag : ";
cin>>wt;
int P[n] , W[n];
cout<<"Enter weights : ";
for(int i=0 ; i<n ; i++)
cin>>W[i];
cout<<"Enter profits: ";
for(int i=0 ; i<n ; i++)
cin>>P[i];
cout<<"Maximum weight that can be assigned is : "<<UKS(W , P , wt , n);
return 0;
}