Skip to content

Commit c37769e

Browse files
authored
Merge pull request #506 from RAUNAK-PANDEY/Raunak
Unbounded Knapsack in C++ #441
2 parents 9441d1f + c7faf1f commit c37769e

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
//Link: https://practice.geeksforgeeks.org/problems/knapsack-with-duplicate-items4201/1
2+
3+
/*
4+
Knapsack with Duplicate Items :
5+
Given a set of N items, each with a weight and a value, and a weight limit W. Find the maximum value of a collection containing any of the N items any number of times so that the total weight is less than or equal to W.
6+
7+
8+
9+
Example 1:
10+
11+
Input: N = 2, W = 3
12+
val[] = {1, 1}
13+
wt[] = {2, 1}
14+
Output: 3
15+
Explaination: Pick the 2nd element thrice.
16+
17+
18+
Example 2:
19+
20+
Input: N = 4, W = 8
21+
val[] = {1, 4, 5, 7}
22+
wt[] = {1, 3, 4, 5}
23+
Output: 11
24+
Explaination: The optimal choice is to
25+
pick the 2nd and 4th element.*/
26+
// Initial Template for C++
27+
28+
#include <bits/stdc++.h>
29+
using namespace std;
30+
31+
// } Driver Code Ends
32+
// User function Template for C++
33+
34+
class Solution{
35+
public:
36+
int knapSack(int N, int W, int val[], int wt[])
37+
{
38+
// code here
39+
int dp[N+1][W+1];
40+
memset(dp,-1,sizeof(dp));
41+
42+
for(int i=0;i<N+1;i++)
43+
{
44+
for(int j=0;j<W+1;j++)
45+
{
46+
if(i==0 || j==0)
47+
{
48+
dp[i][j]=0;
49+
}
50+
//Here if weight is less than j it wont be considered processed and we will consider it multiple times. that's why we write val[i-1]+dp[i][j-wt[i-1]] instead of val[i-1]+dp[i-1][j-wt[i-1]]
51+
else if(wt[i-1]<=j){
52+
dp[i][j]= max(val[i-1]+dp[i][j-wt[i-1]] , dp[i-1][j]);
53+
}
54+
else{
55+
dp[i][j] = dp[i-1][j];
56+
}
57+
}
58+
}
59+
return dp[N][W];
60+
}
61+
};
62+
63+
// { Driver Code Starts.
64+
65+
int main(){
66+
int t;
67+
cin>>t;
68+
while(t--){
69+
int N, W;
70+
cin>>N>>W;
71+
int val[N], wt[N];
72+
for(int i = 0;i < N;i++)
73+
cin>>val[i];
74+
for(int i = 0;i < N;i++)
75+
cin>>wt[i];
76+
77+
Solution ob;
78+
cout<<ob.knapSack(N, W, val, wt)<<endl;
79+
}
80+
return 0;
81+
} // } Driver Code Ends

0 commit comments

Comments
 (0)