File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change
1
+ var coinChange = function ( coins , amount ) {
2
+ // create a dp array that stores the minimum amount of coins used for each amount leading up to the target amount
3
+ // fill with array with amount + 1 as a default
4
+ const dp = [ 0 , ...new Array ( amount ) . fill ( amount + 1 ) ] ;
5
+
6
+ // loop through the coins
7
+ for ( const coin of coins ) {
8
+ // for each amount, assess how the current coin can modify the existing value within the dp array by comparing the min value
9
+ for ( let i = 1 ; i <= amount ; i ++ ) {
10
+ // only works if coin is less than or equal to the assessing amount
11
+ if ( coin <= i ) {
12
+ // min comparison
13
+ dp [ i ] = Math . min ( dp [ i ] , dp [ i - coin ] + 1 ) ;
14
+ }
15
+ }
16
+ }
17
+ // check target amount in dp array to see if it's the default value
18
+ // if it's default value, it means coin combination cannot lead up to target amount
19
+ // if it's not default value, that is the minimum required coin change to lead up to target amount
20
+ return dp [ amount ] === amount + 1 ? - 1 : dp [ amount ] ;
21
+ } ;
22
+
23
+ // time - O(a * c) loops through amount * loops through coin
24
+ // space - O(a) depends on the size of amount
You can’t perform that action at this time.
0 commit comments