File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ function rob ( nums : number [ ] ) : number {
2+ // ์ฒซ์๋: ์์ ๋จ์ด์ ธ์๋ ๊ฒฝ์ฐ๋ฅผ ๊ณ ๋ คํ์ง ์์ (ํต๊ณผ ์๋จ)
3+ // let evenSum = 0;
4+ // let oddSum = 0;
5+
6+ // for (let i=0; i<nums.length; i++) {
7+ // if (i % 2 === 0) {
8+ // evenSum += nums[i];
9+ // } else {
10+ // oddSum += nums[i];
11+ // }
12+ // }
13+
14+ // return Math.max(evenSum, oddSum);
15+
16+ // ์๊ฐ๋ณต์ก๋ O(n), ๊ณต๊ฐ๋ณต์ก๋ O(1)
17+ if ( nums . length === 0 ) return 0 ;
18+ if ( nums . length === 1 ) return nums [ 0 ] ;
19+
20+ let prev = nums [ 0 ] ;
21+ let max = Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
22+
23+ for ( let i = 2 ; i < nums . length ; i ++ ) {
24+ const current = Math . max ( max , prev + nums [ i ] ) ;
25+ prev = max ;
26+ max = current ;
27+ }
28+
29+ return max ;
30+ } ;
You canโt perform that action at this time.
0 commit comments