KatInterview

Minimize Payment Transfers to Balance Group Accounts

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingbacktrackingmemoizationcombinatorial-search

Last updated

Tests backtracking with memoization to find the smallest number of payments needed to settle net balances across multiple participants.

A group of people have been tracking their shared expenses. You receive a log of transactions where each entry transactions[i] = [payer, recipient, amount] means person payer paid amount dollars on behalf of person recipient.

Each person has a net balance: the total they paid for others minus the total others paid for them. To balance everyone's accounts, participants must make direct payments to each other until every person's net balance reaches zero.

Your task is to determine the minimum number of direct payments required to settle all accounts.

Constraints

  • 1 <= len(transactions) <= 1000
  • Each transaction is [payer, recipient, amount] where payer != recipient
  • 0 <= payer, recipient <= 100
  • 1 <= amount <= 1000
  • The number of people with non-zero net balances will not exceed 12

Examples

Example 1

Input: min_payments_to_settle([[0, 1, 10], [2, 0, 5]])

Output: 2

Example 2

Input: min_payments_to_settle([[0, 1, 10], [1, 0, 1], [1, 2, 5], [2, 0, 5]])

Output: 1

Hints

Hint 1

The original transaction history doesn't matter—only each person's net balance (what they're owed or what they owe) is relevant.

Hint 2

A group of k people whose net balances sum to zero can always be settled in k-1 payments, but finding the true minimum requires checking if the group can be split into independent subgroups.

Hint 3

Use backtracking: pick one person with a non-zero balance, try settling their entire debt with each person of opposite sign, then recursively solve the remaining balances. Memoize on the sorted balance tuple to avoid recomputing identical states.