#2591

Distribute Money to Maximum Children

Easy
MathGreedyGreedyMathematical Constraints
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach calculates the maximum number of children that can receive 8 dollars directly by checking the constraints of the remaining money and children. This avoids unnecessary iterations and checks.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the maximum possible k as min(children, money // 8).
  2. 2Step 2: Calculate the remaining money after giving k children 8 dollars.
  3. 3Step 3: Check if the remaining money can be distributed among the remaining children without violating the rules.
  4. 4Step 4: If valid, return k. If not, decrement k and repeat until a valid distribution is found or return -1.
solution.py8 lines
1def maxChildren(money, children):
2    max_k = min(children, money // 8)
3    for k in range(max_k, -1, -1):
4        remaining_money = money - k * 8
5        remaining_children = children - k
6        if remaining_money >= remaining_children and remaining_money != 4 * remaining_children:
7            return k
8    return -1

Complexity note: The time complexity is O(n) because we check each possible k only once, leading to a linear scan.

  • 1Distributing money must consider both the total amount and the constraints on individual amounts.
  • 2The problem can be approached by iterating downwards from the maximum possible distribution to find the first valid configuration.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.