Skip to main content
1 of 2

In linear time, you can find the median item in terms of value per unit weight. Then, also in linear time, you can figure out if you can fit all items that are at least that valuable in the knapsack or not. If you can, then do so, and recursively solve this problem for the n/2 items of lower value given that you've already filled the knapsack. If you can't, then you can throw out the n/2 items of lower value, and then try to solve the problem again with only the n/2 items of highest value.

The recurrence here is T(n)=T(n/2)+O(n), and we have that T(n)=O(n), as desired.

In the solution you have pasted:

The R1, R2, R3 are further subsets of the ratio set depending on the ratio being less, equal or greater than that of the median element.

similarly, the W1, W2, W3 are the summation of the weights of these sets.

Now choose the suitable solution set depending on the ratio values as explained in starting.