Skip to content

Commit d892dcb

Browse files
committedMar 16, 2025
Add solution #808
1 parent 872436e commit d892dcb

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,7 @@
616616
804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy|
617617
805|[Split Array With Same Average](./0805-split-array-with-same-average.js)|Hard|
618618
806|[Number of Lines To Write String](./0806-number-of-lines-to-write-string.js)|Easy|
619+
808|[Soup Servings](./0808-soup-servings.js)|Medium|
619620
819|[Most Common Word](./0819-most-common-word.js)|Easy|
620621
821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy|
621622
824|[Goat Latin](./0824-goat-latin.js)|Easy|

‎solutions/0808-soup-servings.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)
Please sign in to comment.