Skip to content

Commit 243f35d

Browse files
committed
house robber solution
1 parent 54cbbb5 commit 243f35d

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

โ€Žhouse-robber/yeeZinu.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
var rob = function (nums) {
2+
const n = nums.length;
3+
4+
// ๊ธธ์ด๊ฐ€ 1์ด๋ผ๋ฉด
5+
if (n === 1) {
6+
return nums[0];
7+
}
8+
9+
// nums์˜ ๊ธธ์ด๋งŒํผ 0์œผ๋กœ ์ดˆ๊ธฐํ™”๋œ ๋ฐฐ์—ด
10+
const dp = Array(n).fill(0);
11+
12+
// 0๋ฒˆ์€ nums[0]
13+
dp[0] = nums[0];
14+
// 1๋ฒˆ์€ 0๊ณผ 1์ค‘ ํฐ๊ฒƒ์„ ์„ ํƒ
15+
dp[1] = Math.max(nums[0], nums[1]);
16+
17+
// i-1 ๊ณผ i + i-2 ์˜ ํ•ฉ์ค‘ ๋” ํฐ๊ฒƒ์„ ์„ ํƒํ•˜๋ฉด๋จ
18+
for (let i = 2; i < n; i++) {
19+
dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
20+
}
21+
// i๊ฐ€ n - 1๊นŒ์ง€ ๋ฐ˜๋ณตํ•จ
22+
return dp[n - 1];
23+
};

0 commit comments

Comments
ย (0)