File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * [Idea]
3+ * μ΄λ€ μ§μ ν΄λ€κ³ νμ λ μ΅λ κΈμ‘μ ꡬνλ μμ μλμ κ°μ΄ μΈμΈ μ μλ€.:
4+ * Math.max(μ μ§μ νΈμμ λμ μ΅λ κΈμ‘, μ μ μ§μ νΈμμ λμ μ΅λ κΈμ‘ + μ§κΈ μ§μ νΈμμ λ μ»λ κΈμ‘) => DP
5+ * μ°μ° νμλ₯Ό μ€μ¬μ£ΌκΈ° μν΄μ λ©λͺ¨ λ°°μ΄μ μ΄μ©νλ€.
6+ *
7+ * [Time Complexity]
8+ * O(n)
9+ * for loop μμ nums λ°°μ΄μ κ° μμμ νλ²μ©λ§ μ κ·Όνλ―λ‘ O(n)
10+ *
11+ * [Space Complexity]
12+ * O(n)
13+ * λ©λͺ¨ λ°°μ΄μ μν μΆκ° 곡κ°
14+ */
15+ function rob ( nums : number [ ] ) : number {
16+ const n = nums . length ;
17+ if ( n === 1 ) {
18+ return nums [ 0 ] ;
19+ }
20+
21+ // idx μ§μ ν°λ κ²½μ° vs μ ν°λ κ²½μ°λ₯Ό λΉκ΅ν΄μ ν° κ°μ μ μ₯νλ dp λ°°μ΄
22+ const memo = new Array ( n ) . fill ( 0 ) ;
23+ memo [ 0 ] = nums [ 0 ] ;
24+ memo [ 1 ] = Math . max ( memo [ 0 ] , nums [ 1 ] ) ;
25+
26+ for ( let idx = 2 ; idx < n ; idx ++ ) {
27+ // idxλ²μ§Έ μ§μμμ μ΅λ κΈμ‘ = idxλ²μ§Έ μ§μ ν°λ κ²½μ° vs μ ν°λ κ²½μ° μ€ μ΅λκ°
28+ memo [ idx ] = Math . max ( memo [ idx - 2 ] + nums [ idx ] , memo [ idx - 1 ] ) ;
29+ }
30+
31+ return memo [ n - 1 ] ;
32+ }
You canβt perform that action at this time.
0 commit comments