Skip to content

Commit 8f66c84

Browse files
committed
House Robber 풀이 1 #264
1 parent de8a7a0 commit 8f66c84

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

house-robber/seungseung88.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// 시간 복잡도: O(n) 한 번의 루프만 돎
2+
// 공간 복잡도: O(n) nums와 같은 길이의 dp배열 생성
3+
4+
const rob = (nums) => {
5+
if (nums.length === 0) return 0;
6+
if (nums.length === 1) return nums[0];
7+
8+
const dp = Array(nums.length - 1).fill(0);
9+
10+
dp[0] = nums[0];
11+
dp[1] = Math.max(nums[0], nums[1]);
12+
13+
for (let i = 2; i < nums.length; i += 1) {
14+
dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]);
15+
}
16+
17+
return dp[nums.length - 1];
18+
};

0 commit comments

Comments
 (0)