leetcode - 465. Optimal Account Balancing

Description

You are given an array of transactions transactions where transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi gave amounti $ to the person with ID = toi.

Return the minimum number of transactions required to settle the debt.

Example 1:

Input: transactions = [[0,1,10],[2,0,5]]
Output: 2
Explanation:
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.

Example 2:

Input: transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
Output: 1
Explanation:
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.

Constraints:

1 <= transactions.length <= 8
transactions[i].length == 3
0 <= fromi, toi < 12
fromi != toi
1 <= amounti <= 100

Solution

Solved after help.

Run a debt list, to store all the balance of people. Then backtrace, every time assume we use the first additive inverse number to pay all the balance[start_index].

Time complexity: o ( 2 n ) = o ( 2 8 ) o(2^n)=o(2^8) o(2n)=o(28)
Space complexity: o ( n ) o(n) o(n)

Code

class Solution:
    def minTransfers(self, transactions: List[List[int]]) -> int:
        user_balance = {}
        for a, b, amount in transactions:
            user_balance[a] = user_balance.get(a, 0) - amount
            user_balance[b] = user_balance.get(b, 0) + amount
        balance = sorted(item for item in user_balance.values() if item != 0)
        def dfs(start_index: int) -> int:
            while start_index < len(balance) and balance[start_index] == 0:
                start_index += 1
            if start_index == len(balance):
                return 0
            res = float('inf')
            for i in range(start_index + 1, len(balance)):
                if balance[i] * balance[start_index] < 0:
                    balance[i] += balance[start_index]
                    res = min(res, 1 + dfs(start_index + 1))
                    balance[i] -= balance[start_index]
            return res if res != float('inf') else 0
        return dfs(0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值