Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

465. Optimal Account Balancing #9

Open
box-lin opened this issue Jul 1, 2023 · 0 comments
Open

465. Optimal Account Balancing #9

box-lin opened this issue Jul 1, 2023 · 0 comments

Comments

@box-lin
Copy link
Owner

box-lin commented Jul 1, 2023

image
Time: O(n!)
Space: O(n)

class Solution:
    def minTransfers(self, transactions: List[List[int]]) -> int:
        dep = [0] * 12
        for x, y, amount in transactions:
            dep[x] -= amount
            dep[y] += amount
        
        def dfs(i):
            while i < len(dep) and dep[i] == 0: 
                i += 1
            if i >= len(dep):
                return 0
            minop = math.inf
            for j in range(i+1, len(dep)):
                if dep[i] * dep[j] < 0:
                    # we settle up dep[i] by put dep[i] to dep[j]
                    dep[j] += dep[i]
                    minop = min(minop, dfs(i+1) + 1)
                    dep[j] -= dep[i]
            return minop
        return dfs(0)
@box-lin box-lin added this to the Algorithm milestone Jul 1, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant