Skip to content

Commit 08706ec

Browse files
committed
3. House Robber II
1 parent def6a43 commit 08706ec

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

β€Žhouse-robber-ii/sunjae95.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
};

0 commit comments

Comments
Β (0)