#808
Soup Servings
MediumMathDynamic ProgrammingProbability and StatisticsDynamic ProgrammingMemoization
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
For larger values of n, the probabilities stabilize and can be approximated. We can use dynamic programming to store results for smaller values and avoid redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: If n > 5000, return 1.0 as the probability stabilizes.
- 2Step 2: Use a memoization technique to store results of dp(a, b) for each state.
- 3Step 3: Calculate probabilities recursively as in the brute force approach but with memoization.
solution.py18 lines
1# Full working Python code
2from functools import lru_cache
3
4def soupServings(n: int) -> float:
5 if n > 5000:
6 return 1.0
7
8 @lru_cache(None)
9 def dp(a, b):
10 if a <= 0 and b <= 0:
11 return 0.5
12 if a <= 0:
13 return 1.0
14 if b <= 0:
15 return 0.0
16 return 0.25 * (dp(a - 100, b) + dp(a - 75, b - 25) + dp(a - 50, b - 50) + dp(a - 25, b - 75))
17
18 return dp(n, n)ℹ
Complexity note: The time complexity is O(n) due to the memoization of results for each state, which reduces redundant calculations.
- 1The probability stabilizes for large n, allowing us to return a constant value.
- 2Using memoization significantly reduces the number of calculations needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.