KatInterview

Even Budget Split Under Per-Person Caps

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsgreedybinary-searchwater-filling

Last updated

Split a budget as evenly as possible among people with individual caps, using a binary-searched fill level plus a lowest-index-first remainder rule.

Even Budget Split Under Per-Person Caps

A pool holds budget units of money, to be shared among several people. Person i can receive at most caps[i] units. Every amount is a whole number.

The money is handed out one unit at a time, following this rule:

  • Give the next unit to a person who currently holds the smallest amount among everyone who has not yet reached their cap.
  • If several such people are tied, pick the one with the smallest index.
  • Stop when the budget is used up or every person is at their cap.

Return a list with the same length as caps, where entry i is the total amount person i ends up with. If the combined caps are smaller than the budget, the surplus is simply not handed out.

Because the budget can be huge, you cannot simulate it unit by unit. You need a method whose running time does not depend on the size of budget.

Notes on the process

  • Everyone starts with 0.
  • A person who reaches their cap is removed from consideration and never receives more.
  • Two people who are both below their cap can never differ by more than one unit once the process finishes, unless the one holding more is at their own cap.

Constraints

  • 1 <= budget <= 10^9
  • 1 <= len(caps) <= 10^5
  • 1 <= caps[i] <= 10^9
  • All values are integers.
  • The result must have len(caps) entries, with 0 <= result[i] <= caps[i].

Examples

Example 1

Input: split_budget(10, [3, 3, 3])

Output: [3, 3, 3]

Example 2

Input: split_budget(7, [2, 5, 4])

Output: [2, 3, 2]

Hints

Hint 1

Think of the process as raising a common 'level': after enough rounds, person i holds min(caps[i], level). Define total_given(level) as the sum of these values.

Hint 2

total_given(level) never decreases as level grows, so you can binary search for the largest integer level whose total does not exceed the budget.

Hint 3

After fixing that level, some units remain (fewer than the number of people still below their cap). Give one extra unit each to the lowest-index people whose cap is strictly above the level.