Distribute Money to Maximum Children - Problem

You are given an integer money denoting the amount of money (in dollars) that you have and another integer children denoting the number of children that you must distribute the money to.

You have to distribute the money according to the following rules:

  • All money must be distributed.
  • Everyone must receive at least 1 dollar.
  • Nobody receives 4 dollars.

Return the maximum number of children who may receive exactly 8 dollars if you distribute the money according to the aforementioned rules. If there is no way to distribute the money, return -1.

Input & Output

Example 1 — Basic Case
$ Input: money = 20, children = 3
Output: 1
💡 Note: Optimal distribution is [1, 8, 11]. One child gets exactly $8. We can't give two children $8 each because that would leave $4 for the third child, which violates the constraint.
Example 2 — Impossible Case
$ Input: money = 4, children = 2
Output: -1
💡 Note: We have $4 for 2 children. If we give each child at least $1, we need at least $2. The remaining $2 could be distributed as [1, 3] or [2, 2], but we cannot avoid giving someone exactly $4 if we try [0, 4], and $0 violates the minimum constraint.
Example 3 — All Get $8
$ Input: money = 24, children = 3
Output: 3
💡 Note: We can distribute as [8, 8, 8]. All three children get exactly $8, and no constraints are violated.

Constraints

  • 1 ≤ children ≤ 50
  • 1 ≤ money ≤ 200

Visualization

Tap to expand
Distribute Money to Maximum Children INPUT MONEY $20 CHILDREN = 3 1 2 3 RULES: 1. All money distributed 2. Everyone gets >= $1 3. Nobody gets $4 4. Maximize $8 receivers ALGORITHM STEPS 1 Check validity money >= children? 20 >= 3 [OK] 2 Give $1 to each Remaining: 20 - 3 = $17 3 Try max $8 receivers Each needs +$7 more 17/7 = 2 possible 4 Check $4 constraint 2 get $8, 1 gets $4 INVALID! Reduce to 1 Final Distribution: Child1: $8, Child2: $9, Child3: $3 Total: 8+9+3 = $20 [OK] FINAL RESULT Maximum Children 1 Distribution: $8 [OK] $9 extra $3 min Output: return 1 Key Insight: Greedy approach: Give $1 to each child first, then try to upgrade as many as possible to $8. Watch for edge case: if last child would get exactly $4, reduce max by 1 and redistribute. Time Complexity: O(1) | Space Complexity: O(1) TutorialsPoint - Distribute Money to Maximum Children | Optimal Solution
Asked in
Amazon 25 Google 18 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen