oneby7

Greedy The best choice now

501. Fractional Knapsack

Medium

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

Output: 83.5

Explanation: 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

Output: 22

Explanation: 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

Output: 2999999997

Explanation: 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.

values = [20, 9, 2] weights = [10, 3, 2] capacity = 6

Constraints

  • 1 ≤ n ≤ 105
  • values.length = weights.length = n
  • 1 ≤ values[i], weights[i] ≤ 109
  • 1 ≤ capacity ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.