1452. Stop or Reroll
At a fairground stall you roll a fair die with faces numbered 1 to faces, and the number on your last roll is your prize in tokens. You may roll at most rolls times. After any roll you may stop and keep that roll, or (if rolls remain) discard it and roll again; a roll you discard is gone for good. You play to maximise the expected prize.
Return that optimal expected prize as a double; an absolute or relative error of 1e-6 is accepted. Let E(t) be the best expectation with t rolls left. Each E(t) must be computed in O(1) from E(t - 1) using sums of consecutive integers, giving O(rolls) time and O(1) space.
Example 1
- Input:
- faces = 6, rolls = 1
- Output:
- 3.5
- Explanation:
- With one roll you must keep it, so the expectation is (1+2+...+6)/6 = 3.5.
Example 2
- Input:
- faces = 6, rolls = 2
- Output:
- 4.25
- Explanation:
- After a first roll you reroll when it is below 3.5, giving (4+5+6+3*3.5)/6 = 4.25.
Example 3
- Input:
- faces = 2, rolls = 3
- Output:
- 1.875
- Explanation:
- With two faces and three rolls the values go 1.5, then 1.75, then 1.875.
Constraints
1 ≤ faces ≤ 106
1 ≤ rolls ≤ 106
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(rolls)
- Space
- O(1)