Posted: 9 Dec, 2020
You have been given weights and values of ‘N’ items. You are also given a knapsack of size ‘W’.
Your task is to put the items in the knapsack such that the total value of items in the knapsack is maximum.
You are allowed to break the items.
If 'N = 4' and 'W = 10'. The weights and values of items are weights = [6, 1, 5, 3] and values = [3, 6, 1, 4]. Then the best way to fill the knapsack is to choose items with weight 6, 1 and 3. The total value of knapsack = 3 + 6 + 4 = 13.00
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows. The first line of each test case contains two single space-separated integers ‘N’ and ‘W’, respectively. The second line of each test case contains ‘N’ single space-separated integers representing the weight of the i-th item. The third line of each test case contains ‘N’ single space-separated integers representing the value of the i-th item.
For each test case, the only line of output will print the maximum total value of items in the knapsack. The output must be rounded correctly up to two decimal places. Print the output of each test case in a separate line.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 100 1 <= N <= 5000 1 <= W <= 10^5 1 <= weights[i] <= 10^5 1 <= values[i] <= 10^5 Time limit: 1 sec
The key observation here is that we need to pick items which have higher value/weight ratio.
Here is the algorithm:
- We will calculate the ratio of value/weight for each item.
- Sort the items in decreasing order based on this ratio.
- We take the item with the highest ratio first and add them until we can’t add a whole item.
- Add the next item as much as we can.