File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * time complexity: O(2^n)
4+ * space complexity: O(n)
5+ * 풀이 실패
6+ * 풀이 방법: 선택한 경우와 선택하지 않은 경우를 재귀적으로 호출하여 최대값을 반환한다.
7+ * @param {number[] } nums
8+ * @return {number }
9+ */
10+ const rob = function ( nums ) {
11+ console . log ( nums ) ;
12+ if ( nums . length === 0 ) return 0 ;
13+ if ( nums . length === 1 ) return nums [ 0 ] ;
14+ if ( nums . length === 2 ) return Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
15+
16+ // 선택한 경우
17+ const selected = nums [ 0 ] + rob ( nums . slice ( 2 ) ) ;
18+ // 선택하지 않은 경우
19+ const unselected = rob ( nums . slice ( 1 ) ) ;
20+
21+ const max = Math . max ( selected , unselected ) ;
22+
23+ return max ;
24+ } ;
25+
26+ /**
27+ * @description
28+ * time complexity: O(n)
29+ * space complexity: O(n)
30+ * runtime: 100ms
31+ * 풀이 방법: 위 풀이가 타임아웃이 남, DP로 풀어야함을 인지 후 풀이 방법 변경
32+ * @param {number[] } nums
33+ * @return {number }
34+ */
35+ const robSolution2 = function ( nums ) {
36+ const dp = new Array ( nums . length ) . fill ( 0 ) ;
37+
38+ dp [ 0 ] = nums [ 0 ] ;
39+ dp [ 1 ] = Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
40+
41+ for ( let i = 2 ; i < nums . length ; i += 1 ) {
42+ dp [ i ] = Math . max ( dp [ i - 1 ] , dp [ i - 2 ] + nums [ i ] ) ;
43+ }
44+
45+ return dp [ nums . length - 1 ] ;
46+ } ;
You can’t perform that action at this time.
0 commit comments