1501. Best Ratio of K Picks

Hard7.5 points estimatedBinary SearchGreedySorting

A team lead must pick exactly k of n tasks. Task i earns values[i] points and costs weights[i] hours. Choose exactly k distinct tasks to maximise the total points divided by the total hours, and return that best ratio as a double; answers within 1e-6 absolute or relative error are accepted.

Binary search the ratio r: it is reachable exactly when the k largest values of values[i] - r * weights[i] sum to at least 0, so on each trial compute the adjusted scores, sort them and add up the top k. Target O(n log n * log(range / precision)) time and O(n) extra space.

Example 1

Input:
values = [10,4,6], weights = [5,2,4], k = 2
Output:
2
Explanation:

Tasks 0 and 1 give (10 + 4) / (5 + 2) = 2, better than the other two pairs.

Example 2

Input:
values = [0,0], weights = [1,1], k = 1
Output:
0
Explanation:

Every task earns zero points, so the best ratio is 0.

Example 3

Input:
values = [8], weights = [3], k = 1
Output:
2.666666666666667
Explanation:

With a single task the ratio is 8 / 3, about 2.6667.

Constraints

1 ≤ k ≤ n ≤ 1000; 0 ≤ values[i] ≤ 106; 1 ≤ weights[i] ≤ 106; absolute or relative error 1e-6

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 * log(range / precision))
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…