Skip to content

Commit d052748

Browse files
Create Unbounded_knapsack.cpp
1 parent dd36279 commit d052748

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
The Unbounded Knapsack problem allows you to take unlimited quantities of each item. The goal is to maximize the total value
3+
without exceeding the given knapsack capacity. Unlike the 0/1 knapsack, where each item can be taken only once, in this
4+
variation, you can pick any item as many times as needed, as long as the total weight stays within the knapsack's capacity.
5+
The problem is commonly solved using dynamic programming.
6+
7+
TASK - Given a set of N items, each with a weight and a value, represented by the array wt and val respectively. Also, a knapsack with weight limit W.
8+
The task is to fill the knapsack in such a way that we can get the maximum profit. Return the maximum profit.
9+
Note: Each item can be taken any number of times.
10+
11+
Test Cases -
12+
Input:
13+
N = 4, W = 8, val[] = {6, 1, 7, 7}, wt[] = {1, 3, 4, 5}
14+
Output:
15+
48
16+
*/
17+
18+
// Code
19+
#include <bits/stdc++.h>
20+
using namespace std;
21+
22+
int KnapSackFilling(int i,int W, vector<int> val,vector<int> wt, vector<vector<int>> &dp){
23+
if(i==0){
24+
if(wt[0]<=W){
25+
return (W/wt[0])*val[0];
26+
}else{
27+
return 0;
28+
}
29+
}
30+
if(dp[i][W]!=-1)return dp[i][W];
31+
int nottake=KnapSackFilling(i-1,W,val,wt,dp);
32+
int take=0;
33+
if(W>=wt[i]){
34+
take=val[i]+KnapSackFilling(i,W-wt[i],val,wt,dp);
35+
}
36+
return dp[i][W]=max(take,nottake);
37+
}
38+
int unboundedKnapsack(int N, int W, vector<int> val, vector<int> wt)
39+
{
40+
vector<vector<int>> dp(N,vector<int>(W+1,-1));
41+
return KnapSackFilling(N-1,W,val,wt,dp);
42+
}
43+
int main() {
44+
int N;
45+
N=4;
46+
vector<int> wt= {1, 3, 4, 5};
47+
vector<int> val= {6, 1, 7, 7};
48+
int W = 8;
49+
50+
cout << "The Maximum value of items is " << unboundedKnapsack(N, W, val, wt) << endl;
51+
52+
return 0;
53+
}
54+

0 commit comments

Comments
 (0)