File: distribute-money-to-maximum-children/solution.py

Date: 2026-06-06

Time: 16:25

Purpose

This file implements LeetCode 2591: Distribute Money to Maximum Children. It solves a greedy distribution problem: given money dollars and children recipients, maximize the number of children who receive exactly $8, subject to two constraints — every child must get at least $1, and no child can receive exactly $4.

The file is self-contained: solution function, test suite, and entrypoint all live in one module. It follows the repo-wide convention of solution.py per problem directory.

Key Components

maximumchildrenwitheightdollars(money, children) -> int

The core solver. Contract:

TestMaximumChildrenWithEightDollars

11 unit tests covering the impossible case, exact-fit cases, and both special edge-case corrections.

Flow

The algorithm works in four steps:

1. Feasibility check (line 16): if money < children, return -1 — can't give everyone the minimum $1.

2. Baseline allocation (line 18): give every child $1, leaving remaining = money - children. Each "$8 child" now needs $7 more (since they already have $1).

3. Greedy assignment (line 19): eights = min(remaining // 7, children) — as many $8 recipients as the budget allows, capped by child count.

4. Correction for two forbidden states:

Patterns

Dependencies

Invariants

1. Every child receives at least $1 — enforced by the money < children guard.

2. No child receives exactly $4 — enforced by the others == 1 and leftover == 3 correction.

3. All money is distributed — enforced by the eights == children and leftover > 0 correction (surplus can't vanish; someone must absorb it).

4. The return value is in [-1, children].

Error Handling

No exceptions. The single error state (impossible distribution) is signaled by the -1 return value, matching LeetCode's API contract.