Menu
CoddyTech

Fractional Knapsack

MediumGreedySortingpython iconjava iconcpp iconc iconjs icon+10

You have n items. Item i is worth values[i] and weighs weights[i]. Your bag holds a total weight of at most capacity, and you may take any part of an item: a piece of item i that weighs w is worth values[i] × w / weights[i].

Write a function named fractionalKnapsack that returns the largest total value the bag can carry, rounded down to a whole number.

Function

fractionalKnapsack(values: integer-array, weights: integer-array, capacity: integer) → integer
valuesinteger-array
the value of each item
weightsinteger-array
the weight of each item
capacityinteger
the most weight the bag can hold
Returnsinteger
the largest total value that fits in the bag, rounded down

Constraints

  • 1 ≤ n ≤ 5000, where n = values.length = weights.length
  • 1 ≤ values[i], weights[i] ≤ 104
  • 1 ≤ capacity ≤ 108

Examples

Input
values = [40, 90, 30, 50]weights = [8, 30, 5, 20]capacity = 40
Output
151
Explanation
Per unit of weight the items are worth 5, 3, 6 and 2.5. Items 2 and 0 go in whole for 70 with room for 27 left, and 27 of item 1's 30 units add 81, for 151.
challenge icon

Follow-up

Can you find the answer in O(n) time, without sorting all the items?

Reset code
def fractionalKnapsack(values, weights, capacity):
    # Write code here

Test #1

Test #2

Test #3

Arguments

values = [40, 90, 30, 50]
weights = [8, 30, 5, 20]
capacity = 40

Expected Output

151