|
| 1 | +/** |
| 2 | + * 808. Soup Servings |
| 3 | + * https://leetcode.com/problems/soup-servings/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. |
| 7 | + * There are four kinds of operations: |
| 8 | + * 1. Serve 100 ml of soup A and 0 ml of soup B, |
| 9 | + * 2. Serve 75 ml of soup A and 25 ml of soup B, |
| 10 | + * 3. Serve 50 ml of soup A and 50 ml of soup B, and |
| 11 | + * 4. Serve 25 ml of soup A and 75 ml of soup B. |
| 12 | + * |
| 13 | + * When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will |
| 14 | + * choose from the four operations with an equal probability 0.25. If the remaining volume of |
| 15 | + * soup is not enough to complete the operation, we will serve as much as possible. We stop once |
| 16 | + * we no longer have some quantity of both types of soup. |
| 17 | + * |
| 18 | + * Note that we do not have an operation where all 100 ml's of soup B are used first. |
| 19 | + * |
| 20 | + * Return the probability that soup A will be empty first, plus half the probability that A and B |
| 21 | + * become empty at the same time. Answers within 10-5 of the actual answer will be accepted. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number} n |
| 26 | + * @return {number} |
| 27 | + */ |
| 28 | +var soupServings = function(n) { |
| 29 | + if (n >= 4800) return 1.0; |
| 30 | + |
| 31 | + n = Math.ceil(n / 25); |
| 32 | + const memo = new Map(); |
| 33 | + |
| 34 | + function calculateProbability(a, b) { |
| 35 | + if (a <= 0 && b <= 0) return 0.5; |
| 36 | + if (a <= 0) return 1.0; |
| 37 | + if (b <= 0) return 0.0; |
| 38 | + |
| 39 | + const key = a * 10000 + b; |
| 40 | + if (memo.has(key)) return memo.get(key); |
| 41 | + |
| 42 | + const probability = 0.25 * ( |
| 43 | + calculateProbability(a - 4, b) + calculateProbability(a - 3, b - 1) |
| 44 | + + calculateProbability(a - 2, b - 2) + calculateProbability(a - 1, b - 3) |
| 45 | + ); |
| 46 | + |
| 47 | + memo.set(key, probability); |
| 48 | + return probability; |
| 49 | + } |
| 50 | + |
| 51 | + return calculateProbability(n, n); |
| 52 | +}; |
0 commit comments