File tree Expand file tree Collapse file tree 1 file changed +90
-0
lines changed Expand file tree Collapse file tree 1 file changed +90
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * brainstorming:
4+ * 1. asc sort + division calculate
5+ * 2. bfs + memoization
6+ *
7+ * strategy:
8+ * bfs + memoization
9+ *
10+ * reason:
11+ * Tried with brainstorming 1 but test case is false
12+ *
13+ * time complexity: O(n^k)
14+ * space complexity: O(n)
15+ */
16+ class Node {
17+ constructor ( val ) {
18+ this . value = val ;
19+ this . next = null ;
20+ }
21+ }
22+
23+ class CustomQueue {
24+ constructor ( ) {
25+ this . front = null ;
26+ this . rear = null ;
27+ this . size = 0 ;
28+ }
29+
30+ push ( val ) {
31+ const node = new Node ( val ) ;
32+
33+ if ( this . size === 0 ) {
34+ this . front = node ;
35+ this . rear = node ;
36+ } else {
37+ this . rear . next = node ;
38+ this . rear = node ;
39+ }
40+
41+ this . size ++ ;
42+ }
43+
44+ pop ( ) {
45+ if ( this . size === 0 ) return null ;
46+ const node = this . front ;
47+ this . front = this . front . next ;
48+ this . size -- ;
49+ if ( this . size === 0 ) this . rear = null ;
50+
51+ return node . value ;
52+ }
53+ }
54+
55+ var coinChange = function ( coins , amount ) {
56+ const queue = new CustomQueue ( ) ;
57+ const memoSet = new Set ( ) ;
58+
59+ if ( amount === 0 ) return 0 ;
60+
61+ for ( const coin of coins ) {
62+ if ( amount === coin ) return 1 ;
63+
64+ queue . push ( coin ) ;
65+ memoSet . add ( coin ) ;
66+ }
67+
68+ let count = 1 ;
69+
70+ while ( queue . size ) {
71+ count ++ ;
72+ let depthSize = queue . size ;
73+
74+ while ( depthSize -- ) {
75+ const sum = queue . pop ( ) ;
76+
77+ for ( const coin of coins ) {
78+ const nextSum = sum + coin ;
79+
80+ if ( memoSet . has ( nextSum ) ) continue ;
81+ if ( amount === nextSum ) return count ;
82+ if ( amount > nextSum ) queue . push ( nextSum ) ;
83+
84+ memoSet . add ( nextSum ) ;
85+ }
86+ }
87+ }
88+
89+ return - 1 ;
90+ } ;
You can’t perform that action at this time.
0 commit comments