KatInterview

Balance Wealth Through Optimal Integer Transfers

Greedy & IntervalsAuto-graded · 23 test cases
MediumAuto-gradedGreedy & Intervalsgreedytwo-pointersmath

Last 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:

  1. All wealth values and transfers must be integers
  2. The total sum of wealth must remain unchanged
  3. 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 r people one extra unit (where r is 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