A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for Bill's lunch for $10. Then later Chris gave Alice $5 for a taxi ride. We can model each transaction as a tuple (x, y, z) which means person x gave person y $z. Assuming Alice, Bill, and Chris are person 0, 1, and 2 respectively (0, 1, 2 are the person's ID), the transactions can be represented as [[0, 1, 10], [2, 0, 5]].

Given a list of transactions between a group of people, return the minimum number of transactions required to settle the debt.

Note:

A transaction will be given as a tuple (x, y, z). Note that x ≠ y and z > 0.
Person's IDs may not be linear, e.g. we could have the persons 0, 1, 2 or we could also have the persons 0, 2, 6.
Example 1:

Input:
[[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:
[[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.
Show Company Tags

Backtracking: time complexity O(N!)

Use HashMap to store the initial debts of each person, negative means the person sends money to others, positive means the person gets money from others.

now if the map value is 0, which means the person is all set, free of debts.

Only consider those people with debts(either positive or negative)

store them in an array, use backtracking and greedy to clear each person's debts from 1st person till last one.

How to clear one person's debt? find a person 2 in the following array that has opposite sign(+->-  or - -> +), and clear person1's whole debt with person2 only.

Here's the trick: example: [7, -6, -1], one obvious optimal solution is person1 pay $6 to person2, and pay $1 to person3. Notice that this optimal solution is equivalent to another solution:

person1 pay $7 to person2, and person2 pay $1 to person3. So when doing DFS, everytime we only consider clearing person1's debt wholly with another 1 person, we don't need to consider clearing with other more people, cause clearing with 1 person is already guaranteed to be optimal.

This problem still has some debates in discussion, will check later

 public class Solution {
     int res = Integer.MAX_VALUE;
     public int minTransfers(int[][] transactions) {
         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
         for (int[] transaction : transactions) {
             map.put(transaction[0], map.getOrDefault(transaction[0], 0)-transaction[2]);
             map.put(transaction[1], map.getOrDefault(transaction[1], 0)+transaction[2]);
         }
         ArrayList<Integer> depts = new ArrayList<Integer>();
         for (int dept : map.values()) {
             if (dept != 0) depts.add(dept);
         }
         helper(depts, 0, 0);
         return res;
     }

     public void helper(ArrayList<Integer> depts, int start, int count) {
         while (start<depts.size() && depts.get(start)==0) start++;
         if (start == depts.size()) {
             res = Math.min(res, count);
             return;
         }
         for (int i=start+1; i<depts.size(); i++) {
             if (depts.get(start)<0&&depts.get(i)>0 || depts.get(start)>0&&depts.get(i)<0) {
                 depts.set(i, depts.get(i)+depts.get(start));
                 //int store = depts.get(start);
                 //depts.set(start, 0);
                 helper(depts, start+1, count+1);
                 //depts.set(start, store);
                 depts.set(i, depts.get(i)-depts.get(start));
             }
         }
     }
 }

Leetcode: Optimal Account Balancing的更多相关文章

  1. [LeetCode] Optimal Account Balancing 最优账户平衡

    A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for ...

  2. [LeetCode] 465. Optimal Account Balancing 最优账户平衡

    A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for ...

  3. LC 465. Optimal Account Balancing 【lock,hard】

    A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for ...

  4. [LeetCode] Optimal Division 最优分隔

    Given a list of positive integers, the adjacent integers will perform the float division. For exampl ...

  5. LeetCode Optimal Division

    原题链接在这里:https://leetcode.com/problems/optimal-division/description/ 题目: Given a list of positive int ...

  6. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  7. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  8. All LeetCode Questions List 题目汇总

    All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...

  9. Leetcode problems classified by company 题目按公司分类(Last updated: October 2, 2017)

    All LeetCode Questions List 题目汇总 Sorted by frequency of problems that appear in real interviews. Las ...

随机推荐

  1. iOS 隐藏键盘的几种常见方法

    1.设置return key,然后为Did End On Exit事件添加响应方法,并在方法内添加代码:[self.textfieldName resignFirstResponder]. 2.将背景 ...

  2. 每日一问:面试结束时面试官问"你有什么问题需要问我呢",该如何回答?

    面试结束时面试官问"你有什么问题需要问我呢",该如何回答?

  3. [软件推荐]Windows文件夹多标签工具Clover

    Clover 是 Windows Explorer 资源管理器的一个扩展,为其增加类似谷歌 Chrome 浏览器的多标签页功能,目前最新版本为:3.1.7 Clover 把 Chrome 标签页有的样 ...

  4. PHP-Redis扩展使用手册(一)

    //初始化redis实例 $redis = new Redis(); /* connect . open 链接redis * @param string host redis服务器地址 * @para ...

  5. jsonp模拟获取百度搜索相关词汇

    随便写了个jsonp模拟百度搜索相关词汇的小demo,帮助新手理解jsonp的用法. <!DOCTYPE html><html lang="en">< ...

  6. ANSI_NULLS和QUOTED_IDENTIFIER

    这些是 SQL-92 设置语句,使 SQL Server 2000/2005 遵从 SQL-92 规则. 当 SET QUOTED_IDENTIFIER 为 ON 时,标识符可以由双引号分隔,而文字必 ...

  7. 【Leetcode】Longest Palindromic Substring

    问题:https://leetcode.com/problems/longest-palindromic-substring/ 给定一个字符串 S,求出 S 的最长回文子串 思路: 1. 回文:一个字 ...

  8. java中强制类型转换

    在Java中强制类型转换分为基本数据类型和引用数据类型两种,这里我们讨论的后者,也就是引用数据类型的强制类型转换. 在Java中由于继承和向上转型,子类可以非常自然地转换成父类,但是父类转换成子类则需 ...

  9. JVM内存区域异常分析

    在Java虚拟机规范描述中,除程序计数器外,其他几个运行时区域都有可能发生OutOfMemoryError异常.接下来将对各区域分别进行分析介绍,内容包括触发各区域OutOfMemoryError异常 ...

  10. 数据库使用数据泵迁移遇到LOB字段

    impdp system/Clic1234 attach=SYS_IMPORT_ILEARN_TRA desc ILEARN_TRA.NOTIFI_TACTIC desc ILEARN_TRA.MSG ...