this is a typical Knapsack problem requiring dynamic programming and there is no constraint on the supply of items. I've been working on this for my class and I tried to play around with the algorithm for hours and I'm still not getting there.
public static int fitBackPack(int[] W, int[] V, int T){
int[] Opt = new int[T+1];
Opt[0]=0;
for (int i=1; i<=T; i++){
int localMax=0;
int globalMax=0;
for (int j=0; j<W.length; j++){
if (W[j]<=i){
localMax = (T%W[j]<=W[j]) ? V[j] : V[j]+Opt[T-W[j]];
globalMax = (localMax>=globalMax) ? localMax : globalMax;
}
}
Opt[i]=globalMax;
}
//debugging purposes
for (int k=0; k<Opt.length; k++){
System.out.println("Opt["+k+"] = "+Opt[k]);
}
return Opt[T];
}
This method is supposed to take a sorted array of W and V, containing the weight and the value of the item respectively, and an integer T representing the max weight. For my output, everything up until T=21 works, however, after that it just seems to be working like a greedy algorithm, which is completely not what I was hoping for. Any hints will be appreciated, thanks!