Payments app~25 min2s · 256 MBtarget O(n × total) time, O(total) spacedp
A currency app shows the exchange rate of one currency pair. A simple model says that each day the rate moves by a known number of ticks. It moves up or down with equal chance, independently of the other days.
The risk team asks one question: what is the probability that, after all the days, the rate ended above where it started? The answer is a fraction, so it is reported modulo the prime 998,244,353.
Write probability_above_start(moves).
moves[i] is the size in ticks of the move on day i. On each day the rate goes up by moves[i] with probability 1/2, or down by moves[i] with probability 1/2.a / b. Return a × b^-1 modulo 998,244,353, where b^-1 is the modular inverse of b. The denominator is a power of 2, so it always has an inverse.Input: moves = [1, 2, 3]
Output: 623902721The table counts the choices of up days by their total.
| Sum of the up moves | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Choices of days | 1 | 1 | 1 | 2 | 1 | 1 | 1 |
| Above the start (2 × sum > 6)? | no | no | no | no | yes | yes | yes |
There are 2^3 = 8 ways to choose up or down. The table counts, for each sum of the days that go up, how many choices give it. The ways with 2 × sum above 6 are the sums 4, 5 and 6, so 1 + 1 + 1 = 3 ways. The probability is 3/8, and 3 × 8^-1 modulo 998,244,353 is the output.
Input: moves = [5]
Output: 499122177One day: the rate ends above the start with probability 1/2, which is the modular inverse of 2.
Input: moves = [1, 1]
Output: 748683265Of the four choices, only up-up ends above the start. The probability is 1/4. Two days with a tie end exactly at the start, which is not above it.
1 ≤ moves.length ≤ 400 (days)1 ≤ moves[i] ≤ 10 (ticks)The result is a whole number from 0 to 998,244,352.
Trying every up and down choice costs about 2^n steps, which is far beyond any computer at n = 400. The rate can only end at one of at most 8,001 positions, and many choices lead to the same one. Counting choices by their total, day by day, costs about n × total steps, about 1.6 × 10^6.