File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed
Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Source: https://leetcode.com/problems/house-robber/
3+ * ํ์ด๋ฐฉ๋ฒ: DP๋ฅผ ์ด์ฉํ์ฌ ์ง์ ํธ ๋ ์ต๋๊ฐ์ ๊ตฌํจ
4+ * ์๊ฐ๋ณต์ก๋: O(n)
5+ * ๊ณต๊ฐ๋ณต์ก๋: O(n)
6+ *
7+ * ์๊ฐ๋๋ ํ์ด๋ฐฉ๋ฒ
8+ */
9+ function rob ( nums : number [ ] ) : number {
10+ if ( nums . length === 0 ) return 0 ;
11+ if ( nums . length === 1 ) return nums [ 0 ] ;
12+ if ( nums . length === 2 ) return Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
13+
14+ const dp : number [ ] = new Array ( nums . length ) ;
15+
16+ dp [ 0 ] = nums [ 0 ] ;
17+ dp [ 1 ] = Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
18+
19+ // ๋จ์ ์ง์ ์ํํ๋ฉด์ ์ต๋๊ฐ์ ๊ตฌํจ
20+ for ( let i = 2 ; i < nums . length ; i ++ )
21+ dp [ i ] = Math . max ( dp [ i - 1 ] , dp [ i - 2 ] + nums [ i ] ) ;
22+
23+ return dp [ nums . length - 1 ] ;
24+ }
You canโt perform that action at this time.
0 commit comments