Distribute Money to Maximum Children — LeetCode 2591 Python Solution

EasyGreedyMath
Problem
#2591
Pattern
Greedy
Reading time
2 min

The 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.

Example

Input
money = 20, children = 3
Output
1
Explanation
The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:

Python solution

Python
class Solution:
    def distMoney(self, money: int, children: int) -> int:
        if money < children:
            return -1
        if money > 8 * children:
            return children - 1
        if money == 8 * children - 4:
            return children - 2
        # money-8x >= children-x, x <= (money-children)/7
        return (money - children) // 7

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2591. Distribute Money to Maximum Children is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2591. Distribute Money to Maximum Children?
LeetCode 2591. Distribute Money to Maximum Children is rated Easy on LeetCode.
What topics does LeetCode 2591. Distribute Money to Maximum Children cover?
LeetCode 2591. Distribute Money to Maximum Children is tagged Greedy and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview