Balance Wealth Through Optimal Integer Transfers
Greedy & IntervalsAuto-graded · 23 test casesLast updated
Tests greedy two-pointer coordination and integer division to equalize values with minimal movement.
You are given an array wealth where each element represents the wealth of a person (wealth can be negative, zero, or positive). Your task is to redistribute wealth through direct transfers between people so that everyone's final wealth is as close to equal as possible, while maintaining the same total sum.
Requirements:
- All wealth values and transfers must be integers
- The total sum of wealth must remain unchanged
- Minimize the maximum deviation from perfect equality
Output format:
Return a dictionary with two keys:
"finalWealth": a list of integers representing each person's wealth after redistribution"transfers": a list of transfers, where each transfer is[from_index, to_index, amount]
Rules:
- When the total cannot be divided evenly, distribute the remainder by giving the first
rpeople one extra unit (whereris the remainder) - Each transfer must have a positive amount
- Transfers should move wealth from those above their target to those below their target
Constraints:
0 <= len(wealth) <= 10^4-10^9 <= wealth[i] <= 10^9- The sum of all wealth fits in a 64-bit signed integer
Examples
Example 1
Input: balance_wealth([10, 0, 5])
Output: {'finalWealth': [5, 5, 5], 'transfers': [[0, 1, 5]]}
Example 2
Input: balance_wealth([1, 2, 3, 4])
Output: {'finalWealth': [3, 3, 2, 2], 'transfers': [[2, 0, 1], [3, 0, 1], [3, 1, 1]]}
Example 3
Input: balance_wealth([4, -2, 0])
Output: {'finalWealth': [1, 1, 0], 'transfers': [[0, 1, 3]]}
Hints
Hint 1
Consider what the optimal final distribution looks like when you divide the total by the number of people
Hint 2
Use integer division with remainder - some people will get one more unit than others
Hint 3
Match people who have excess with people who have deficit using a two-pointer greedy approach
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is determining the optimal target wealth distribution when only integers are allowed. We want to minimize the maximum deviation from the mean while preserving the total.
Step 1: Calculate optimal targets
Divide the total sum by the number of people using integer division:
base = total // n(floor division)remainder = total % n
The optimal distribution gives base + 1 to the first remainder people and base to everyone else. This ensures the maximum difference between any two people is at most 1, which is the best possible when dealing with integers.
Step 2: Identify donors and receivers
Compare each person's current wealth to their target:
- If
wealth[i] > final[i], they are a donor with surpluswealth[i] - final[i] - If
wealth[i] < final[i], they are a receiver with deficitfinal[i] - wealth[i]
Step 3: Match donors with receivers greedily
Use two pointers to coordinate transfers:
- Take the current donor and current receiver
- Transfer the minimum of their surplus and deficit
- Advance the pointer for whichever side reached zero (or both)
- Repeat until all surpluses and deficits are resolved
Correctness:
Since the total surplus equals the total deficit (both equal the sum of absolute deviations from targets), the two-pointer scan will exhaust both lists simultaneously. Each transfer moves wealth in the right direction without overshooting, guaranteeing everyone reaches their target.
Complexity:
- Time: O(n) - one pass to compute targets, one to build donor/receiver lists, and at most n-1 transfers
- Space: O(n) - for storing the final wealth array and transfer lists
from typing import Dict, List
def balance_wealth(wealth: List[int]) -> Dict:
n = len(wealth)
if n == 0:
return {"finalWealth": [], "transfers": []}
total = sum(wealth)
base, remainder = divmod(total, n)
# Optimal distribution: first 'remainder' people get base+1, rest get base
final = [base + (1 if i < remainder else 0) for i in range(n)]
# Identify donors (have surplus) and receivers (have deficit)
donors = [[i, wealth[i] - final[i]] for i in range(n) if wealth[i] > final[i]]
receivers = [[i, final[i] - wealth[i]] for i in range(n) if wealth[i] < final[i]]
transfers = []
donor_idx = receiver_idx = 0
while donor_idx < len(donors) and receiver_idx < len(receivers):
transfer_amount = min(donors[donor_idx][1], receivers[receiver_idx][1])
transfers.append([donors[donor_idx][0], receivers[receiver_idx][0], transfer_amount])
donors[donor_idx][1] -= transfer_amount
receivers[receiver_idx][1] -= transfer_amount
if donors[donor_idx][1] == 0:
donor_idx += 1
if receivers[receiver_idx][1] == 0:
receiver_idx += 1
return {"finalWealth": final, "transfers": transfers}