File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ function change ( coins , amount ) {
2
+ const combinations = new Array ( amount + 1 ) . fill ( 0 )
3
+ combinations [ 0 ] = 1
4
+
5
+ for ( let i = 0 ; i < coins . length ; i ++ ) {
6
+ const coin = coins [ i ]
7
+
8
+ for ( let j = coin ; j < amount + 1 ; j ++ ) {
9
+ combinations [ j ] += combinations [ j - coin ]
10
+ }
11
+ }
12
+ return combinations [ amount ]
13
+ }
14
+
15
+ function minimumCoins ( coins , amount ) {
16
+ // minimumCoins[i] will store the minimum coins needed for amount i
17
+ const minimumCoins = new Array ( amount + 1 ) . fill ( 0 )
18
+
19
+ minimumCoins [ 0 ] = 0
20
+
21
+ for ( let i = 1 ; i < amount + 1 ; i ++ ) {
22
+ minimumCoins [ i ] = Number . MAX_SAFE_INTEGER
23
+ }
24
+ for ( let i = 1 ; i < amount + 1 ; i ++ ) {
25
+ for ( let j = 0 ; j < coins . length ; j ++ ) {
26
+ const coin = coins [ j ]
27
+ if ( coin <= i ) {
28
+ const subRes = minimumCoins [ i - coin ]
29
+ if ( subRes !== Number . MAX_SAFE_INTEGER && subRes + 1 < minimumCoins [ i ] ) {
30
+ minimumCoins [ i ] = subRes + 1
31
+ }
32
+ }
33
+ }
34
+ }
35
+ return minimumCoins [ amount ]
36
+ }
37
+
38
+ function main ( ) {
39
+ const amount = 12
40
+ const coins = [ 2 , 4 , 5 ]
41
+ console . log ( 'Number of combinations of getting change for ' + amount + ' is: ' + change ( coins , amount ) )
42
+ console . log ( 'Minimum number of coins required for amount :' + amount + ' is: ' + minimumCoins ( coins , amount ) )
43
+ }
44
+
45
+ main ( )
You can’t perform that action at this time.
0 commit comments