The knapsack can carry a maximum weight , say max_wt ; has n items with a given weightwt[]
and a valueval[]
.I have two questions ( both seperate from each other ) :
- What is the maximum value we can carry if there was a second limit to the volume we could carry , vol[ ] ?
- What are the number of ways to carry a total of exactly z(< n) items such that their sum of values is divisible by a number , say 8 ?
My Attempt
For the first question i refered this stackoverflow post , but the only answer i could understand was one where the two constraints were merged ,but the run time complexity of that would be quite big i guess...what i was thinking was making a
dp[i][j][k]
, where i is the number of items selected , j is the max-wt selected at that point , k is the max-vol selected at that point and then my core of the code looked like
for(i=0 ; i < n ; i++) \\ n is no. of items for(j=0 ; j < n ; j++) for(k=0 ; k < n ; k++) dp[i][j][k] = max( dp[i-1][j][k] , val[i] + dp[i-1][j-wt[j]][k-vol[k]]) ;
, this seems alright , but gives me wrong answer ... i cant guess why :(I can't start to think of the second problem, my friend did it by taking three states dp[i][j][k] where i and j are just same as first question(the usual ones) while 'k' keeps track of the total items selected , this idea isnt getting in my head . Plus , what will a state store , it usually stores max value possible till given state in classical knapsack problems , here i guess a state will store total combinations divisible by 8 till that state , but i cant convert this into code .
p.s please try providing a solution with bottom up approach to the second question , i am very new to dynamic programming . ;)