- 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
- 35 lines of Java from the credited upstream file 1467.java.
- The implementation visibly relies on sequence storage.
- 1 loop block 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.
1enum BoxCase { EQUAL_BALLS, EQUAL_DISTANT_BALLS }2 3class Solution {4 public double getProbability(int[] balls) {5 final int n = Arrays.stream(balls).sum() / 2;6 return cases(balls, 0, 0, 0, 0, 0, n, BoxCase.EQUAL_DISTANT_BALLS) /7 cases(balls, 0, 0, 0, 0, 0, n, BoxCase.EQUAL_BALLS);8 }9 10 private int[] fact = {1, 1, 2, 6, 24, 120, 720};11 12 13 double cases(int[] balls, int i, int ballsCountA, int ballsCountB, int colorsCountA,14 int colorsCountB, int n, BoxCase boxCase) {15 if (ballsCountA > n || ballsCountB > n)16 return 0;17 if (i == balls.length)18 return boxCase == BoxCase.EQUAL_BALLS ? 1 : (colorsCountA == colorsCountB ? 1 : 0);19 20 double ans = 0;21 22 23 for (int ballsTakenA = 0; ballsTakenA <= balls[i]; ++ballsTakenA) {24 final int ballsTakenB = balls[i] - ballsTakenA;25 final int newcolorsCountA = colorsCountA + (ballsTakenA > 0 ? 1 : 0);26 final int newcolorsCountB = colorsCountB + (ballsTakenB > 0 ? 1 : 0);27 ans += cases(balls, i + 1, ballsCountA + ballsTakenA, ballsCountB + ballsTakenB,28 newcolorsCountA, newcolorsCountB, n, boxCase) /29 (fact[ballsTakenA] * fact[ballsTakenB]);30 }31 32 return ans;33 }34}35