KatInterview

Optimal Ball Distribution for Maximum Joint Red Probability

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationprobabilityoptimizationmath

Last updated

Tests ability to formulate and optimize a probability function over discrete allocations with boundary analysis.

You have a collection of red balls and blue balls that must be placed into exactly two containers. Each container must hold at least one ball. You will then select one ball from the first container and one ball from the second container.

Your task is to determine the allocation that maximizes the probability that both selected balls are red, and return that maximum probability.

Write a function that takes the total number of red balls and the total number of blue balls, and returns the highest achievable probability (as a float) that both balls drawn are red.

Constraints:

  • 0 ≤ red_balls ≤ 10^6
  • 0 ≤ blue_balls ≤ 10^6
  • Both containers must be non-empty
  • If it is impossible to draw two red balls (fewer than 2 red balls total), return 0.0

Examples

Example 1

Input: max_red_probability(100, 100)

Output: 0.49748743718592964

Example 2

Input: max_red_probability(10, 10)

Output: 0.47368421052631576

Example 3

Input: max_red_probability(2, 0)

Output: 1

Hints

Hint 1

The probability of both events is the product of two independent draws—one from each container.

Hint 2

One container can achieve probability 1.0 for drawing red if it contains only red balls. What's the minimum cost?

Hint 3

After isolating one red ball by itself, distribute all remaining balls to maximize the red ratio in the other container.