33 * @params {Number} amount
44 */
55export const change = ( coins , amount ) => {
6- // Create and initialize the storage
6+ if ( ! Array . isArray ( coins ) ) {
7+ throw new TypeError ( 'Coins must be an array' )
8+ }
9+
10+ if ( typeof amount !== 'number' || amount < 0 ) {
11+ throw new TypeError ( 'Amount must be a non-negative number' )
12+ }
13+
14+ if ( amount === 0 ) {
15+ return 1
16+ }
17+
18+ if ( coins . length === 0 ) {
19+ return 0
20+ }
21+
722 const combinations = new Array ( amount + 1 ) . fill ( 0 )
823 combinations [ 0 ] = 1
9- // Determine the direction of smallest sub-problem
24+
1025 for ( let i = 0 ; i < coins . length ; i ++ ) {
11- // Travel and fill the combinations array
1226 for ( let j = coins [ i ] ; j < combinations . length ; j ++ ) {
1327 combinations [ j ] += combinations [ j - coins [ i ] ]
1428 }
1529 }
30+
1631 return combinations [ amount ]
1732}
33+
1834/**
1935 * @params {Array} coins
2036 * @params {Number} amount
2137 */
2238export const coinChangeMin = ( coins , amount ) => {
23- const map = { 0 : 1 }
39+ if ( ! Array . isArray ( coins ) ) {
40+ throw new TypeError ( 'Coins must be an array' )
41+ }
42+
43+ if ( typeof amount !== 'number' || amount < 0 ) {
44+ throw new TypeError ( 'Amount must be a non-negative number' )
45+ }
46+
47+ if ( amount === 0 ) {
48+ return 0
49+ }
50+
51+ if ( coins . length === 0 ) {
52+ return - 1
53+ }
54+
55+ const map = { 0 : 0 }
56+
2457 for ( let i = 1 ; i <= amount ; i ++ ) {
2558 let min = Infinity
2659 for ( const coin of coins ) {
@@ -29,5 +62,6 @@ export const coinChangeMin = (coins, amount) => {
2962 }
3063 map [ i ] = min
3164 }
32- return map [ amount ] === Infinity ? - 1 : map [ amount ] - 1
65+
66+ return map [ amount ] === Infinity ? - 1 : map [ amount ]
3367}
0 commit comments