2929: Distribute-Candies-Among-Children-II
Medium

My original set-up was an O(limit) solution, where you iterated from 0 to limit inclusive.

That would represent the candies one of the children would receive. We then check for the largest amount of candies we can distribute to one of the remaining children. It is the minimum value between:

Then, after finding the largest amount of candies we can distribute to one of the remaining children, we can hence calculate the minimum amount of candies we can distribute to the last child.

As long as the minimum that we calculate is smaller than or equal to the maximum, we can add the difference between the two + 1 to find the total number of configurations we can form (if the first child gets i candies).

An example, for n = 6 and limit = 6, if we have i = 1, then:

so we can form 6 configurations:

  1. 1, 0, 5
  2. 1, 1, 4
  3. 1, 2, 3
  4. 1, 4, 2
  5. 1, 4, 1
  6. 1, 5, 0

Code:

class Solution {
public:
    long long distributeCandies(int n, int limit) {
        if (limit*3 < n) {
            return 0;
        } else {
            long long ans = 0;
            for (int i = 0; i <= limit; ++i) {
                int difference = min(n-i, limit);
                if (n-i-difference <= difference) {
                    ans += (2*difference+i-n)+1;
                }
            }
            return ans;
        }
    }
};

Complexity:

Note, there does exist a math solution to this problem, using the inclusion and exclusion property.

Basically, you can use permutations and combinations to calculate:

Since there is overlap between all the sets, using the inclusion and exclusion property, we can effectively calculate the answer in O(1) time:

C(n+2)23×Cn(limit+1)+22+3×Cn2×(limit+1)+22Cn3×(limit+1)+22 C_(n+2)^2 - 3 \times C_{n-(limit+1)+2}^2 + 3 \times C_{n-2 \times (limit+1)+2}^2 - C_{n-3\times(limit+1)+2}^2

Complexity: