- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 44 lines of Python from the credited upstream file 1467.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from enum import Enum2 3 4class BoxCase(Enum):5 EQUAL_DISTANT_BALLS = 06 EQUAL_BALLS = 17 8 9class Solution:10 def getProbability(self, balls: list[int]) -> float:11 n = sum(balls) 212 fact = [1, 1, 2, 6, 24, 120, 720]13 14 def cases(15 i: int,16 ballsCountA: int,17 ballsCountB: int,18 colorsCountA: int,19 colorsCountB,20 boxCase: BoxCase) -> float:21 if ballsCountA > n or ballsCountB > n:22 return 023 if i == len(balls):24 return (1 if boxCase == BoxCase.EQUAL_BALLS25 else colorsCountA == colorsCountB)26 27 ans = 0.028 29 30 for ballsTakenA in range(balls[i] + 1):31 ballsTakenB = balls[i] - ballsTakenA32 newcolorsCountA = colorsCountA + (ballsTakenA > 0)33 newcolorsCountB = colorsCountB + (ballsTakenB > 0)34 ans += (cases(i + 1,35 ballsCountA + ballsTakenA,36 ballsCountB + ballsTakenB,37 newcolorsCountA, newcolorsCountB, boxCase) /38 (fact[ballsTakenA] * fact[ballsTakenB]))39 40 return ans41 42 return (cases(0, 0, 0, 0, 0, BoxCase.EQUAL_DISTANT_BALLS) /43 cases(0, 0, 0, 0, 0, BoxCase.EQUAL_BALLS))44