[LeetCode] Soup Servings

808. Soup Servings

There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations:

  1. Serve 100 ml of soup A and 0 ml of soup B,
  2. Serve 75 ml of soup A and 25 ml of soup B,
  3. Serve 50 ml of soup A and 50 ml of soup B, and
  4. Serve 25 ml of soup A and 75 ml of soup B.

When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.

Note that we do not have an operation where all 100 ml’s of soup B are used first.

Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
unordered_map<int, unordered_map<int, double>> dp;
double helper(int n, int m, double prop) {
if(n <= 0 and m <= 0) return prop / 2;
if(m <= 0) return 0;
if(n <= 0) return prop;
if(prop < 1e-40) return prop;
if(dp.count(n) and dp[n].count(m)) return dp[n][m];
dp[n][m] = 0;

dp[n][m] += helper(n - 100, m, prop / 4);
dp[n][m] += helper(n - 75, m - 25, prop / 4);
dp[n][m] += helper(n - 50, m - 50, prop / 4);
dp[n][m] += helper(n - 25, m - 75, prop / 4);

return dp[n][m];
}
public:
double soupServings(int n) {
return helper(n, n, 1.0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/13/PS/LeetCode/soup-servings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.