File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * μ νμ: dp[i] = Math.max(dp[i - 1], dp[i - 2] + current);
4+ * μννλ€λ μ‘°κ±΄μ΄ μμΌλ―λ‘ λ€μκ³Ό κ°μ΄ λΆκΈ°μ²λ¦¬ ν μ μλ€.
5+ * 1. μ²μμ΄ μ ν O λ§μ§λ§ X
6+ * 2. μ²μμ΄ μ ν X λ§μ§λ§ μκ΄μμ
7+ *
8+ * n = length of nums
9+ * time complexity: O(n)
10+ * space complexity: O(n)
11+ */
12+ var rob = function ( nums ) {
13+ if ( nums . length === 1 ) return nums [ 0 ] ;
14+ if ( nums . length === 2 ) return Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
15+
16+ const hasFirst = Array . from ( { length : nums . length } , ( _ , i ) =>
17+ i < 2 ? nums [ 0 ] : 0
18+ ) ;
19+ const noFirst = Array . from ( { length : nums . length } , ( _ , i ) =>
20+ i === 1 ? nums [ i ] : 0
21+ ) ;
22+ for ( let i = 2 ; i < nums . length ; i ++ ) {
23+ hasFirst [ i ] = Math . max ( hasFirst [ i - 1 ] , hasFirst [ i - 2 ] + nums [ i ] ) ;
24+ noFirst [ i ] = Math . max ( noFirst [ i - 1 ] , noFirst [ i - 2 ] + nums [ i ] ) ;
25+ if ( i === nums . length - 1 ) {
26+ hasFirst [ i ] = Math . max ( hasFirst [ i - 1 ] , hasFirst [ i - 2 ] ) ;
27+ }
28+ }
29+
30+ return Math . max ( hasFirst [ nums . length - 1 ] , noFirst [ nums . length - 1 ] ) ;
31+ } ;
You canβt perform that action at this time.
0 commit comments