Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Solve LeetCode 2929: Distribute Candies Among Children II in Elixir

Count ordered candy distributions in Elixir by fixing one child’s share and summing the valid interval for the second.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For LeetCode 2929, fix the first child’s share and count the feasible interval of shares for the second. Summing those interval lengths gives a direct Elixir solution in O(min(n, limit)) time and O(1) extra space. The problem asks for the number of ordered ways to distribute all n candies among three distinct children, with each receiving from zero through limit candies.

What counts as a valid distribution?

Each child is distinct, so allocations are ordered: for example, (1, 2, 2), (2, 1, 2), and (2, 2, 1) are three different distributions. Every share must be a nonnegative integer no greater than limit, and the shares must add up to n. LeetCode’s constraints are 1 ≤ n ≤ 10^6 and 1 ≤ limit ≤ 10^6. See the LeetCode problem statement and examples.

As an Amazon Associate I earn from qualifying purchases.

Count allocations by fixing the first child’s share

Let the first child receive i candies. The second child receives j, leaving n - i - j for the third child. The second child’s cap requires j ≤ limit; the third child’s cap requires n - i - j ≤ limit, or j ≥ n - i - limit. Nonnegative shares also require j ≥ 0 and j ≤ n - i.

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

Combining those constraints, the valid values of j form one inclusive interval:

max(0, n - i - limit) ≤ j ≤ min(limit, n - i)

If the lower bound exceeds the upper bound, that first-child share contributes zero. Otherwise, the number of choices for j is upper - lower + 1. Each choice determines exactly one third-child share, so every valid allocation is counted once.

Restrict the first child to feasible shares

The first child can receive at most limit, and the other two can together hold at most 2 * limit. Therefore the feasible range for i is max(0, n - 2 * limit) through min(n, limit), inclusive. If n > 3 * limit, the three children’s total capacity is too small and the answer is zero.

Elixir implementation

defmodule Solution do
  def distribute_candies(n, limit) do
    if n > 3 * limit do
      0
    else
      first_min = max(0, n - 2 * limit)
      first_max = min(n, limit)

      Enum.reduce(first_min..first_max, 0, fn i, total ->
        second_min = max(0, n - i - limit)
        second_max = min(limit, n - i)
        total + max(0, second_max - second_min + 1)
      end)
    end
  end
end

The n > 3 * limit check handles insufficient capacity before constructing the range. Otherwise, the feasible first-share bounds are ordered, including when only a single value is possible. Elixir integers use arbitrary precision, so this calculation does not require fixed-width overflow handling. This is a mathematical translation of the interval count; it has not been run or submitted to LeetCode.

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.

Check the result against the examples

For n = 5 and limit = 2, the first child can receive 1 or 2. If the first receives 1, the second can receive 2, leaving 2; that contributes one. If the first receives 2, the second can receive 1 or 2, contributing two. The total is 3.

For n = 3 and limit = 3, the cap does not exclude any nonnegative split of 3. The count is C(5, 2) = 10, matching LeetCode’s example. These examples are listed in the official problem statement.

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

Alternative: inclusion-exclusion

A constant-time alternative starts with the stars-and-bars count C(n + 2, 2) for distributing candies among three labeled children without caps. Then use inclusion-exclusion to remove cases where one or more children receive more than limit. The LeetCode editorial listing includes this approach alongside enumeration: LeetCode China solution listing.

Approach Runtime Implementation trade-off
Sum feasible intervals O(min(n, limit)) Bounds correspond directly to the share constraints, making the count straightforward to inspect.
Inclusion-exclusion O(1) More compact asymptotically, but translating the formula demands care with the cap and boundary cases.

With the stated maximum input of one million, enumerating the feasible first shares is a practical choice. Prefer the interval sum when clarity and easy auditing matter; use inclusion-exclusion if you want constant-time arithmetic and are comfortable validating its boundary cases.

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

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.

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.