DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
FREEDOM251

Freedom251 › Blog › Algorithms

How to Derive the Formula for Distribute Candies Among Children II

By Freedom251 Team · · 3 min read

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For LeetCode 2929, count ordered triples of nonnegative integers (a, b, c) with a + b + c = n and each value at most limit. Inclusion-exclusion applied to the stars-and-bars count gives C(n+2,2) − 3C(n−limit+1,2) + 3C(n−2limit,2) − C(n−3limit−1,2). Here, define C(x,2) = x(x−1)/2 when x ≥ 2, and C(x,2) = 0 otherwise.

What the formula counts

LeetCode 2929 asks for the number of ways to distribute n candies among three children, with no child receiving more than limit. The children are distinguishable, so changing which child receives an amount creates a different allocation. In symbols, count the ordered triples (a, b, c) satisfying a + b + c = n and 0 ≤ a, b, c ≤ limit. The problem statement gives 1 ≤ n ≤ 106 and 1 ≤ limit ≤ 106 (LeetCode problem statement).

As an Amazon Associate I earn from qualifying purchases.

How inclusion-exclusion produces the formula

Start by counting every nonnegative triple, then remove allocations in which one or more children exceed the cap. A child exceeds the cap by receiving at least limit + 1 candies. Inclusion-exclusion subtracts single-child violations, restores pairwise overlaps, and subtracts the triple overlap.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

1. Count all triples without the cap

By stars and bars, the number of nonnegative integer triples summing to n is C(n + 2, 2). Imagine arranging n candies and inserting two dividers to split them among three children; a section may be empty. This is the unrestricted starting count.

#1 Best Overall
Sale
Cracking the Coding Interview: 189 Programming Questions and Solutions
  • Careercup, Easy To Read
  • Condition : Good
  • Compact for travelling

2. Subtract allocations where one child exceeds the cap

Choose one specified child, say A, and reserve limit + 1 candies for A. After reserving them, n − limit − 1 candies remain to distribute freely among all three children. Stars and bars counts these allocations as:

C((n − limit − 1) + 2, 2) = C(n − limit + 1, 2).

There are three possible children to choose, so subtract 3C(n − limit + 1, 2). The term is zero when too few candies remain to form a distribution.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Restore allocations counted as two violations

If two specified children each receive at least limit + 1, the previous step subtracts that allocation twice. Reserve limit + 1 candies for each of the pair. The leftover is n − 2(limit + 1), and distributing it among three children gives:

C(n − 2(limit + 1) + 2, 2) = C(n − 2limit, 2).

There are three pairs of children, so add 3C(n − 2limit, 2).

4. Subtract the triple overlap

If all three children exceed the cap, the preceding steps restore that allocation once too many. Reserving limit + 1 candies for each leaves n − 3(limit + 1). Its unrestricted distribution count is:

C(n − 3(limit + 1) + 2, 2) = C(n − 3limit − 1, 2).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Subtract this overlap once. Combining the four stages yields:

answer = C(n + 2, 2) − 3C(n − limit + 1, 2) + 3C(n − 2limit, 2) − C(n − 3limit − 1, 2).

Use C(x, 2) = x(x − 1)/2 for x ≥ 2 and zero for x < 2. This convention makes shifted terms vanish when the reserved candies leave too little to distribute, without requiring separate boundary-case formulas. The stars-and-bars and inclusion-exclusion approach is also described in the LeetCode.ca solution explanation.

Check the formula with the official examples

n = 5, limit = 2

C(7, 2) − 3C(4, 2) + 3C(1, 2) − C(−2, 2) = 21 − 18 + 0 − 0 = 3. The valid allocations are the three permutations of (1, 2, 2).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

n = 3, limit = 3

The cap excludes no allocation, so the count is C(5, 2) = 10. Both results match the examples in the LeetCode statement.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

An alternate derivation: fix one child’s share

You can also count by choosing the first child’s amount, then counting the possible amounts for the second. This makes the valid ranges explicit, though summing over the first child is not a constant-time formula.

Find the feasible range for the first child

Call the first child’s share i. It cannot exceed limit, and the other two children can hold at most 2limit together. Therefore:

max(0, n − 2limit) ≤ i ≤ min(n, limit).

Count the second child’s choices for each share

Once i is fixed, the second child’s share j must leave a valid amount for the third child while staying within its own cap:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

max(0, n − i − limit) ≤ j ≤ min(limit, n − i).

Each integer in this inclusive interval gives one valid choice for j and a corresponding third share n − i − j. Thus, for each feasible i, the number of choices is the upper endpoint minus the lower endpoint plus one. Sum that count over the feasible values of i. The interval-based approach is presented in the CodeJeet solution explanation.

Which derivation should you use?

Approach What it emphasizes Counting work Useful when
Stars and bars plus inclusion-exclusion How the closed form follows from unrestricted counts and overlapping violations Constant time: a fixed number of arithmetic operations You want the formula or a direct constant-time implementation
Fix the first child’s share The exact feasible interval for the remaining choices Sum over feasible values of i You want an intuitive enumeration of valid allocations

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Algorithmscombinatoricsinclusion-exclusionLeetCodestars and bars

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.