1736. Risky Quest Order

You are planning a run through a series of risky quests in a game. Quest i succeeds with probability chance[i] / 100 (independently of the others) and pays reward[i] gold on success. You must attempt every quest one after another in an order you choose, but the first failure ends the run immediately, so quests after it are never attempted and pay nothing.

Return the largest possible expected total gold over all orders, as a double (an absolute or relative error of 1e-6 is accepted). Hint: whenever two neighbouring quests can swap, the one with the larger value of chance * reward / (100 - chance) should come first; compare using 64-bit cross-multiplication and sort. Orders that tie give equal expected values. Expected: O(n log n) time, O(n) space.

Example 1

Input:
chance = [50,100], reward = [10,4]
Output:
9
Explanation:

Doing the sure quest (100%, 4 gold) first and then the 50% quest gives 4 + 0.5 * 10 = 9, better than the other order which gives 5 + 0.5 * 4 = 7.

Example 2

Input:
chance = [80,50,10], reward = [10,40,100]
Output:
28
Explanation:

The best order is the 80% quest, then the 50% quest, then the 10% one, giving 10 * 0.8 + 40 * 0.4 + 100 * 0.04 = 28 expected gold (swapping the first two ties).

Constraints

1 ≤ n ≤ 1000

0 ≤ chance[i] ≤ 100

1 ≤ reward[i] ≤ 106

Absolute or relative error 1e-6 accepted.

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

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…