File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } coins
3+ * @param {number } amount
4+ * @return {number }
5+ */
6+
7+ // TC : O(c*a), where c is the number of coins, and a is amount
8+ // SC : O(a) // dp array requires O(a) space
9+
10+ var coinChange = function ( coins , amount ) {
11+ // dynamic programming approach
12+
13+ // dp[amount] : the minimum number of coins
14+ // as a default, dp[0] = 0, for other amounts, dp[amount] = amount + 1 ()
15+ // [0, amount+1, amount+1, ...]
16+ const dp = [ 0 , ...new Array ( amount ) . fill ( amount + 1 ) ] ;
17+
18+ // start from coin because i - coin >= 0
19+ for ( const coin of coins ) {
20+ for ( let i = coin ; i <= amount ; i ++ ) {
21+ // dp[i] : not using the current coin
22+ // dp[i - coin] + 1 : using the current coin
23+ dp [ i ] = Math . min ( dp [ i - coin ] + 1 , dp [ i ] ) ;
24+ }
25+ }
26+
27+ // dp[amount] === amount + 1 : that amount of money cannot be made up by any combination of the coins
28+ return dp [ amount ] < amount + 1 ? dp [ amount ] : - 1 ;
29+ } ;
30+
31+
You can’t perform that action at this time.
0 commit comments