Skip to content

Commit 366886d

Browse files
committed
Add solution #465
1 parent 4a39756 commit 366886d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,7 @@
453453
462|[Minimum Moves to Equal Array Elements II](./solutions/0462-minimum-moves-to-equal-array-elements-ii.js)|Medium|
454454
463|[Island Perimeter](./solutions/0463-island-perimeter.js)|Medium|
455455
464|[Can I Win](./solutions/0464-can-i-win.js)|Medium|
456+
465|[Optimal Account Balancing](./solutions/0465-optimal-account-balancing.js)|Hard|
456457
466|[Count The Repetitions](./solutions/0466-count-the-repetitions.js)|Hard|
457458
467|[Unique Substrings in Wraparound String](./solutions/0467-unique-substrings-in-wraparound-string.js)|Medium|
458459
468|[Validate IP Address](./solutions/0468-validate-ip-address.js)|Medium|
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 465. Optimal Account Balancing
3+
* https://leetcode.com/problems/optimal-account-balancing/
4+
* Difficulty: Hard
5+
*
6+
* You are given an array of transactions transactions where
7+
* transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi
8+
* gave amounti $ to the person with ID = toi.
9+
*
10+
* Return the minimum number of transactions required to settle the debt.
11+
*/
12+
13+
/**
14+
* @param {number[][]} transactions
15+
* @return {number}
16+
*/
17+
var minTransfers = function(transactions) {
18+
const balances = new Array(12).fill(0);
19+
20+
for (const [from, to, amount] of transactions) {
21+
balances[from] -= amount;
22+
balances[to] += amount;
23+
}
24+
25+
const debts = balances.filter(balance => balance !== 0);
26+
return helper(0, 0);
27+
28+
function helper(index, count) {
29+
if (index === debts.length) return count;
30+
31+
if (debts[index] === 0) return helper(index + 1, count);
32+
33+
let minTransactions = Infinity;
34+
const currentDebt = debts[index];
35+
36+
for (let i = index + 1; i < debts.length; i++) {
37+
if (debts[i] * currentDebt < 0) {
38+
debts[i] += currentDebt;
39+
minTransactions = Math.min(minTransactions, helper(index + 1, count + 1));
40+
debts[i] -= currentDebt;
41+
}
42+
}
43+
44+
return minTransactions;
45+
}
46+
};

0 commit comments

Comments
 (0)