-1

This is the old and famous knapsack problem : Knapsack Problem
Here I have Knapsack problem with one constraint.
I have Knapsack with size W = 100000000 and N = 100 items I wrote the dynamic solution for it the Complexity of my algorithm is O(100000000*100) and this is too big in both time and space but there is one condition here that either W ≤ 50000 or max 1≤ i ≤ n Vi ≤ 500. so if my Knapsack size is more than 50000 my maximum value of items is limited.
So now I wonder how can I reduce the time Complexity of my algorithm with this condition I thought Knapsack problem depends on the size of knapsack and the number of items so how the value of items can change the change my algorithm?

Daniel.V
  • 2,322
  • 7
  • 28
  • 58
  • There's a version of the DP that runs in time O(n V) instead of O(n W), where n is the number of items, V is the total (integer) value, and W is the total (integer) weight. – David Eisenstat Jun 23 '15 at 17:15
  • @David Eisenstat relay! would you please guide me more and explain it or give me a link that can help me – Daniel.V Jun 23 '15 at 17:18

1 Answers1

2

Instead of creating a table of size W*n, where each entry D[x][i] indicates the best value (highest) you can get with at most x weight using the first i items, use the table where now D[x][i] is the minimal weight needed to get to value of x, using the first i elements:

D(0,i) = 0                i>0
D(x,0) = infinity         x > 0
D(x,i) = infinity         x<0 or i<0
D(x,i) = min{ D(x,i-1), D(x-value[i],i-1) + weight[i])

When you are done, find max{ x | D(x,n) <= W) } - this is the highest value you can get, using at most W weight, and is done by a linear scan of the last line of the DP matrix.

Checking which variation you need is done by a single scan of the data.

amit
  • 175,853
  • 27
  • 231
  • 333
  • So am I right x should be between 1 and max 1<=i<=max(value) – Daniel.V Jun 23 '15 at 18:30
  • @Daniel.V No, it should be between max and max(value)*100 (assuming 100 different values). – amit Jun 23 '15 at 18:34
  • I know your answer is right but I am confused with your formula can you give a link or a pseudocode – Daniel.V Jun 23 '15 at 18:50
  • @Daniel.V Code will be very similar to "regular" knapsack with the following differences: (1) Table size as we discussed above. (2) Choosing minimum (weight)of the two candidates rather than the maximum (value). (3) weight and value "switch" parts. Do you properly understand "regular" knapsack? If so, this should be fairly easy. – amit Jun 23 '15 at 19:07