Skip to content

Commit 582f532

Browse files
committed
3. House Robber
1 parent 0c6f969 commit 582f532

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @description
3+
* μ΅œλŒ€ν•œ λ§Žμ€ μ–‘μ˜ λˆμ΄λΌλŠ” λ¬Έκ΅¬μ—μ„œ dynamic programming을 연상
4+
* μ—°μ†λœ 집은 ν„Έ 수 μ—†λ‹€λΌλŠ” λ¬Έκ΅¬μ—μ„œ 점화식을 λ„μΆœ ν•  수 μžˆμ—ˆμŒ
5+
*
6+
* n = length of nums
7+
* time complexity: O(n)
8+
* space complexity: O(n)
9+
*/
10+
var rob = function (nums) {
11+
if (nums.length === 1) return nums[0];
12+
13+
const dp = Array(nums.length).fill(0);
14+
15+
dp[0] = nums[0];
16+
dp[1] = Math.max(nums[1], dp[0]);
17+
18+
for (let i = 2; i < nums.length; i++)
19+
dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
20+
21+
return dp[nums.length - 1];
22+
};

0 commit comments

Comments
Β (0)