-
Notifications
You must be signed in to change notification settings - Fork 112
/
0465-OptimalAccountBalancing.cs
70 lines (63 loc) · 2.15 KB
/
0465-OptimalAccountBalancing.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//-----------------------------------------------------------------------------
// Runtime: 104ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
public class _0465_OptimalAccountBalancing
{
public int MinTransfers(int[][] transactions)
{
var balanceMap = new Dictionary<int, int>();
foreach (var transaction in transactions)
{
if (balanceMap.ContainsKey(transaction[0]))
balanceMap[transaction[0]] -= transaction[2];
else
balanceMap[transaction[0]] = -transaction[2];
if (balanceMap.ContainsKey(transaction[1]))
balanceMap[transaction[1]] += transaction[2];
else
balanceMap[transaction[1]] = transaction[2];
}
var balances = balanceMap.Values.Where(x => x != 0).OrderBy(x => x).ToList();
int count = 0;
for (int i = 2; i <= balances.Count; i++)
{
while (HasSubsetSum(balances, 0, i))
{
count += i - 1;
balances = balances.Where(x => x != int.MinValue).OrderBy(x => x).ToList();
}
}
return count;
}
private bool HasSubsetSum(List<int> list, int sum, int num)
{
if (num == 0) return sum == 0;
if (num == 1)
{
var index = list.BinarySearch(sum);
if (index >= 0)
{
list[index] = int.MinValue;
return true;
}
else
return false;
}
for (int i = 0; i < list.Count; i++)
{
if (list[i] == 0) continue;
var value = list[i];
list[i] = int.MinValue;
if (HasSubsetSum(list, sum - value, num - 1)) return true;
list[i] = value;
}
return false;
}
}
}