File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ // n: amount m: length of coins
2+ // Time complexity: O(n * m) + O(mlogm)
3+ // Space complexity: O(n * m)
4+
5+ /**
6+ * @param {number[] } coins
7+ * @param {number } amount
8+ * @return {number }
9+ */
10+ var coinChange = function ( coins , amount ) {
11+ const dp = Array . from ( { length : coins . length + 1 } , ( ) =>
12+ Array . from ( { length : amount + 1 } , ( ) => Infinity )
13+ ) ;
14+ coins . sort ( ( a , b ) => a - b ) ;
15+
16+ for ( let i = 0 ; i < coins . length + 1 ; i ++ ) {
17+ dp [ i ] [ 0 ] = 0 ;
18+ }
19+
20+ for ( let i = 1 ; i <= amount ; i ++ ) {
21+ for ( let j = 1 ; j <= coins . length ; j ++ ) {
22+ const coin = coins [ j - 1 ] ;
23+
24+ if ( i >= coin ) {
25+ dp [ j ] [ i ] = Math . min ( dp [ j ] [ i ] , 1 + dp [ j ] [ i - coin ] ) ;
26+ }
27+
28+ dp [ j ] [ i ] = Math . min ( dp [ j ] [ i ] , dp [ j - 1 ] [ i ] ) ;
29+ }
30+ }
31+
32+ return dp . at ( - 1 ) . at ( - 1 ) === Infinity ? - 1 : dp . at ( - 1 ) . at ( - 1 ) ;
33+ } ;
You can’t perform that action at this time.
0 commit comments