There are two types of soup: type A and type B. Initially, we have N
ml of soup A and N
ml of soup B. We serve soup according to the following probability operations:
We stop serving the soup when either type of soup becomes empty or both become empty. The operation of serving soup obeys this hierarchy:
Return the probability that soup A will be empty first, plus half the probability that A and B will become empty at the same time.
Before we proceed, let’s clarify a few details:
N
to be large, possibly requiring optimization techniques?Assuming the above information is standard:
probability(A, B)
which returns the desired probability for given amounts A and B.Given the memoization approach, the complexity is O(N^2) in terms of states (A, B).
Let’s implement this solution in C++:
#include <map>
#include <utility>
using namespace std;
class Solution {
public:
map<pair<int, int>, double> memo;
double probability(int A, int B) {
if (A <= 0 && B <= 0) return 0.5;
if (A <= 0) return 1.0;
if (B <= 0) return 0.0;
if (memo.find({A, B}) != memo.end()) {
return memo[{A, B}];
}
double result = 0.25 * (probability(A - 100, B) +
probability(A - 75, B - 25) +
probability(A - 50, B - 50) +
probability(A - 25, B - 75));
memo[{A, B}] = result;
return result;
}
double soupServings(int N) {
if (N > 4800) return 1.0; // Fast return for large N based on empirical observations
return probability(N, N);
}
};
memo
to store and reuse results.probability
calculates the probability based on recursive states.N
: If N is larger than a threshold (4800), return 1.0 directly as the probability asymptotically approaches 1.0.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?