Greedy The best choice now
501. Fractional Knapsack
You are given n items and a bag. Item i is worth values[i] and weighs weights[i]. The bag holds at
most capacity units of weight. Return the largest total value you can put in the bag.
You may cut an item and take any part of it. Taking a fraction f of item i, with f between 0 and 1,
adds f · weights[i] to the weight in the bag and f · values[i] to its value. Each item can be taken at
most once, so the most you can take of it is the whole item.
The answer is a floating-point number, and different correct ways of calculating it can round differently in the last digits. So an answer counts as right when it is within 10−6 of the expected answer, or, for an expected answer larger than 1, within 10−6 times that answer.
Example 1
Input: values = [21, 50, 60, 30]
weights = [6, 10, 30, 4]
capacity = 15
83.5Explanation: Per unit of weight, the items are worth 3.5, 5, 2 and 7.5. Take all of item 3 and all of item 1, which weigh 14 and are worth 80. The last unit of space takes 1/6 of item 0, worth 21 / 6 = 3.5.
Example 2
Input: values = [7, 3, 12]
weights = [2, 5, 4]
capacity = 100
22Explanation: All three items weigh 11 together, so they all fit, and the answer is 7 + 3 + 12 = 22. The bag does not have to be full.
Example 3
Input: values = [1000000000, 1000000000, 1000000000]
weights = [1, 2, 1000000000]
capacity = 1000000000
2999999997Explanation: Items 0 and 1 weigh 3 together and fit whole. The other 999999997 units of space take that much of item 2, which is worth 1 per unit of weight.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 105values.length = weights.length = n1 ≤ values[i], weights[i] ≤ 1091 ≤ capacity ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.