1746. Boost the Pass Rate

Medium3.5 points estimatedHeapGreedy

A school has n classes. In class i, passed[i] of the totals[i] students passed the last exam. A tutoring programme can bring in extra additional students who are guaranteed to pass, and each one joins a single class, raising both its passed and total counts by one. No class may receive more than cap of them, and any students who cannot be placed anywhere because every class is full are simply dropped.

The pass rate of a class is passed divided by total. Place the students one at a time to maximize the average of the class pass rates, and return that maximum average as a double (answers within 1e-6 are accepted). The gain of each placement shrinks as a class grows, so always choose the class with the largest gain using a max-heap and compare gains exactly with cross multiplication; ties go to the smaller class index.

Example 1

Input:
passed = [1,1]totals = [2,4]extra = 1cap = 1
Output:
0.4583333333333333
Explanation:

One extra student helps the 1/2 class more (gain 1/6) than the 1/4 class (gain 3/20), giving rates 2/3 and 1/4 with average 11/24.

Example 2

Input:
passed = [2,3]totals = [3,4]extra = 2cap = 1
Output:
0.775
Explanation:

With a cap of 1 each class takes one extra student, so the rates become 3/4 and 4/5 and the average is 0.775.

Example 3

Input:
passed = [1]totals = [2]extra = 5cap = 2
Output:
0.75
Explanation:

Only two extra students fit into the single class, giving 3/4; the other three are dropped.

Constraints

1 ≤ n ≤ 1000 (n = passed.length = totals.length)
1 ≤ passed[i] ≤ totals[i] ≤ 105
1 ≤ extra ≤ 104
1 ≤ cap ≤ 104

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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O((n + extra) 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…