Skip to content

Commit 347d259

Browse files
committed
feat(soobing): week1 > house-robber
1 parent 53ce7c7 commit 347d259

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

house-robber/soobing2.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 문제 유형: DP
3+
*
4+
* 문제 설명
5+
* - 바로 옆집을 한번에 털 수 없을때, 최대로 털 수 있는 돈을 구하는 문제
6+
* - 함정은, 홀수의 합 vs 짝수의 합만 비교해서는 안된다. 2개 초과해서 털 수 있는 경우가 있음 (ex. [2, 1, 1, 2])
7+
*
8+
* 아이디어
9+
* - DP 문제 답게 Top-down, Bottom-up 두 개 다 풀 수 있음
10+
*/
11+
12+
function robBottomUp(nums: number[]): number {
13+
const n = nums.length;
14+
const dp = Array(n).fill(0);
15+
16+
if (n === 1) return nums[0];
17+
if (n === 2) return Math.max(nums[0], nums[1]);
18+
19+
dp[0] = nums[0];
20+
dp[1] = Math.max(nums[0], nums[1]);
21+
22+
for (let i = 2; i < n; i++) {
23+
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
24+
}
25+
26+
return dp[n - 1];
27+
}
28+
29+
function robTopDown(nums: number[]): number {
30+
const n = nums.length;
31+
const memo = new Map<number, number>();
32+
33+
const dp = (i: number) => {
34+
if (i < 0) return 0;
35+
if (memo.has(i)) return memo.get(i);
36+
37+
const res = Math.max(dp(i - 1)!, dp(i - 2)! + nums[i]);
38+
memo.set(i, res);
39+
return res;
40+
};
41+
return dp(n - 1)!;
42+
}

0 commit comments

Comments
 (0)