LeetCode - 808. Soup Servings

Medium
Problem
There are two types of soup: type A and type B, each starting with n
ml. On every turn, one of the following four operations is chosen at random, each with probability 0.25
:
- Serve 100 ml of soup A and 0 ml of soup B
- Serve 75 ml of soup A and 25 ml of soup B
- Serve 50 ml of soup A and 50 ml of soup B
- Serve 25 ml of soup A and 75 ml of soup B
If the remaining volume of a soup is insufficient, pour all that remains. The process stops once at least one soup is depleted. Return the probability that A becomes empty before B, plus half the probability that both become empty at the same time. Answers within 10^-5
are accepted.
Example 1:
Input: n = 50
Output: 0.62500
Explanation:
- Operation 1 & 2 → A empty first
- Operation 3 → both empty same turn
- Operation 4 → B empty first
Summing probabilities:0.25*(1 + 1 + 0.5 + 0) = 0.625
Example 2:
Input: n = 100
Output: 0.71875
Constraints:
0 <= n <= 10^9
解題思路
先把問題縮小
因為每次倒湯的量都是 25 的倍數,所以可以直接把n
換成m = ceil(n / 25)
,這樣狀態就從原本的 n 級別,變成 m 級別,瞬間小很多超大數直接跳過計算
實測發現n >= 5000
的時候,機率已經接近到 1(差距小於 10^-5),
所以可以直接 return1.0
,根本不用跑 DP,可以省很多時間狀態定義
設dp[i][j]
表示 A 剩 i 單位、B 剩 j 單位時,A 先空的機率 + 同時空的一半機率邊界條件
- A ≤ 0 且 B ≤ 0 → 同時空 → 回傳 0.5
- A ≤ 0 且 B > 0 → A 先空 → 回傳 1.0
- B ≤ 0 且 A > 0 → B 先空 → 回傳 0.0
轉移公式
四種操作機率一樣,每種 0.25,所以直接平均四個下一狀態的值Time & Space Complexity
- 最多狀態數是 m²,其中 m ≈ n/25。
- 但因為直接砍掉
n ≥ 5000
的情況,當 n < 5000 時 m 大約是 200,所以實際時間複雜度是 O(1) 級別,空間也是 O(1)
因為註解是邊解邊寫的,我覺得我註解寫的比較容易理解,可以直接看註解去理解這題 XD
Solution Code
1 | class Solution { |