Who owes who money optimization

后端 未结 10 1282
暗喜
暗喜 2020-12-14 02:18

Say you have n people, each who owe each other money. In general it should be possible to reduce the amount of transactions that need to take place. i.e. if X owes Y £4 and

10条回答
  •  误落风尘
    2020-12-14 02:57

    for each debt in debts
      debt.creditor.owed -= debt.amount
      debt.deptor.owed += debt.amount
    end
    
    for each person in persons
      if person.owed > 0 then
        deptors.add person
      else if person.owed < 0 then
        creditors.add person
      end
    end
    
    deptors.sort_by_owed_desc
    creditor.sort_by_owed_asc
    
    for each debtor in deptors
      while debtor.owed > 0
        creditor = creditors.top
        amount = min( debtor.owed, -creditor.owed)
        creditor.owed += amount
        debtor.owed -= amount
        if creditor.owed == 0 then
          creditors.remove_top
        end
        write debtor.name " owes " creditor.name " " amount "€"
      end
    end
    

提交回复
热议问题