Fairly Distribute Money With Limits
GustoSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to implement a greedy allocation algorithm while respecting individual upper bounds and handling iterative redistribution of remaining resources.
Fairly Distribute Money With Limits
You are tasked with distributing a total amount of money total among n recipients. Each recipient has a specific limit which represents the maximum amount of money they are allowed to receive. Your goal is to distribute the money as evenly as possible.
Specifically, follow these rules:
- No recipient can receive more than their
limit. - The distribution should be as "fair" as possible: if you have leftover money after distributing an initial amount, you must distribute the remainder by giving 1 unit to the recipient who currently has the least amount and is below their limit, until the money runs out.
- Return an array of size
nrepresenting the amount each recipient receives.
Function Signature
def distribute_money(total: int, limits: List[int]) -> List[int]:
Constraints
1 <= total <= 10^91 <= n <= 10^51 <= limits[i] <= 10^9
Example 1
Input: total = 10, limits = [3, 3, 3]
Output: [3, 3, 3] (with 1 leftover, which cannot be assigned as everyone is at their limit)
Example 2
Input: total = 7, limits = [2, 5, 4]
Output: [2, 3, 2]
Explanation: Start by giving everyone an equal share or filling based on limits. In this case, 7 is split to ensure no one exceeds their limit while keeping the difference between recipients minimal.
Hints
Hint 1
Consider first checking if the total money exceeds the sum of all limits, as you cannot distribute more than the total sum of limits.
Hint 2
Think about using binary search on the 'target value' that every recipient should reach, or sorting the limits to simplify the greedy distribution process.
Hint 3
If you sort the limits, you can subtract the minimum limit from all others to reduce the problem size iteratively.
Follow-up questions
- What is the time complexity of your solution, and can you optimize it if `total` is significantly larger than the sum of limits?
- How would your algorithm change if every recipient had a minimum requirement that must be satisfied before any 'fair' distribution begins?
- If this were a system with high concurrency where multiple processes are distributing funds, how would you ensure data consistency without locking all recipients?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.