1

You are given a set of bars of gold and your goal is to take as much gold as possible into your bag. There is just one copy of each bar and for each bar you can either take it or not (hence you cannot take a fraction of a bar). Problem Description Task. Given n gold bars, find the maximum weight of gold that fits into a bag of capacity W. Input Format. The first line of the input contains the capacity W of a knapsack and the number n of bars of gold. The next line contains n integers w0,w1,...,wn−1 defining the weights of the bars of gold. Constraints. 1 ≤ W ≤ 104; 1 ≤ n ≤ 300; 0 ≤ w0,...,wn−1 ≤ 105. Output Format. Output the maximum weight of gold that fits into a knapsack of capacity W. here is my code.

#include <bits/stdc++.h>
using namespace std;
int optimal(vector<int>&w,int W,int n){
vector<vector<int> > val(n+2,vector<int>(W+2));

  for(int j=0;j<=n;j++)
  {
for(int i=0;i<=W;i++)
  { if(i==0 || j==0){ val[j][i]=0;continue;}
    if(w[j]<=i)
    {
        val[j][i]=max(val[j-1][i],(w[j]+val[j-1][i-w[j]]));
        //cout<<val[j][i]<<endl;
    }
    else {val[j][i]=val[j-1][i];

  }}
  }
  int q1=val[n][W];
  return q1;
}
int main() {
  int n, W;
  std::cin >> W >> n;
  vector<int> w;
  w.push_back(0);
  for (int i = 1; i <= n; i++) {
    std::cin >> w[i];
  }
 sort(w.begin(),w.end());
cout<<optimal(w,W,n);
}

I cant figure out the solution of this problem.Would be really grateful for any help in this matter .TIA.

  • Israt, Courera's honor code forbids to post your solutions publicly, even if they are not correct. Please remove your solution from here. – Artur Riazanov May 21 '20 at 12:07

0 Answers0