Skip to content

Commit 8d6b849

Browse files
committed
Add solution #322
1 parent 85b2553 commit 8d6b849

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@
215215
290|[Word Pattern](./0290-word-pattern.js)|Easy|
216216
295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard|
217217
316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium|
218+
322|[Coin Change](./0322-coin-change.js)|Medium|
218219
326|[Power of Three](./0326-power-of-three.js)|Easy|
219220
328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium|
220221
334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium|

solutions/0322-coin-change.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 322. Coin Change
3+
* https://leetcode.com/problems/coin-change/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array coins representing coins of different denominations and an
7+
* integer amount representing a total amount of money.
8+
*
9+
* Return the fewest number of coins that you need to make up that amount. If that amount of
10+
* money cannot be made up by any combination of the coins, return -1.
11+
*
12+
* You may assume that you have an infinite number of each kind of coin.
13+
*/
14+
15+
/**
16+
* @param {number[]} coins
17+
* @param {number} amount
18+
* @return {number}
19+
*/
20+
var coinChange = function(coins, amount) {
21+
const counts = new Array(amount + 1).fill(amount + 1);
22+
counts[0] = 0;
23+
24+
for (let i = 1; i <= amount; i++) {
25+
for (let j = 0; j < coins.length; j++) {
26+
if (i - coins[j] >= 0) {
27+
counts[i] = Math.min(counts[i], 1 + counts[i - coins[j]]);
28+
}
29+
}
30+
}
31+
32+
return counts[amount] !== amount + 1 ? counts[amount] : -1;
33+
};

0 commit comments

Comments
 (0)