1728. Fractional Cargo

Easy1.5 points estimatedGreedySortingCustom Comparator

A cargo ship has a weight limit of capacity. Item i weighs weights[i] and is worth values[i], and each item is a loose bulk good: you may load any fraction of it, and its value scales proportionally with the amount loaded. The total loaded weight must not exceed capacity.

Return the maximum total value that can be loaded, as a double; answers within 1e-6 of the true value are accepted. Order the items by value per unit of weight, highest first, comparing two items by cross-multiplication instead of division, then fill the ship greedily, taking a fraction of the first item that does not fit. This takes O(n log n) time and O(n) space.

Example 1

Input:
weights = [4,3,6], values = [8,9,6], capacity = 7
Output:
17
Explanation:

Take the whole second item (value 9) then the whole first item (value 8), filling weight 7 exactly: 17.

Example 2

Input:
weights = [5,2], values = [10,8], capacity = 4
Output:
12
Explanation:

Take the dense item (value 8, weight 2) and 2/5 of the other item (value 4): 12.

Example 3

Input:
weights = [2,3], values = [5,7], capacity = 100
Output:
12
Explanation:

Everything fits, so the value is the sum of all values: 12.

Constraints

1 ≤ n ≤ 1000

1 ≤ weights[i], values[i] ≤ 104

1 ≤ capacity ≤ 107

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…