Skip to content

Commit 13422b1

Browse files
committed
add solution : 213. House Robber II
1 parent e10ec05 commit 13422b1

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

โ€Žhouse-robber-ii/mmyeon.tsโ€Ž

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
*@link https://leetcode.com/problems/house-robber-ii/description/
3+
*
4+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
5+
* - DP๋ฅผ ํ™œ์šฉํ•ด์„œ ํ˜„์žฌ ์œ„์น˜๊นŒ์ง€์˜ ์ตœ๋Œ€๊ฐ’์„ ์—…๋ฐ์ดํŠธ
6+
* - ์›ํ˜• ๊ตฌ์กฐ๋กœ ์ฒซ ๋ฒˆ์งธ ์ง‘๊ณผ ๋งˆ์ง€๋ง‰ ์ง‘์ด ๋‘˜๋‹ค ํฌํ•จ๋  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์—, ์ฒซ ๋ฒˆ์งธ ์ง‘๋งŒ ํฌํ•จํ•˜๋Š” ๊ฒฝ์šฐ์™€ ์ฒซ ๋ฒˆ์งธ ์ง‘์„ ์ œ์™ธํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ ์„œ ๊ณ„์‚ฐํ•˜๊ณ  ์ตœ๋Œ€๊ฐ’ ๋น„๊ต
7+
*
8+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n)
9+
* - n = numbs ๋ฐฐ์—ด์˜ ๊ธธ์ด, n๋ฒˆ ๋ฐ˜๋ณตํ•˜๋ฉด์„œ ์ตœ๋Œ€๊ฐ’ ๊ณ„์‚ฐ
10+
*
11+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(1)
12+
* - dp ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•˜๋Š” ๋Œ€์‹  ๊ณ ์ •๋œ ๋ฐฐ์—ด(prev, doublePrev)์„ ์‚ฌ์šฉ
13+
*/
14+
const calculateMaxMoney = (houses: number[]) => {
15+
let prev = 0;
16+
let doublePrev = 0;
17+
18+
for (let i = 0; i < houses.length; i++) {
19+
const current = Math.max(prev, doublePrev + houses[i]);
20+
21+
doublePrev = prev;
22+
prev = current;
23+
}
24+
25+
return prev;
26+
};
27+
28+
function rob(nums: number[]): number {
29+
if (nums.length === 1) return nums[0];
30+
if (nums.length === 2) return Math.max(nums[0], nums[1]);
31+
32+
const robWithFirstHouse = calculateMaxMoney(nums.slice(0, nums.length - 1));
33+
const robWithoutFirstHouse = calculateMaxMoney(nums.slice(1, nums.length));
34+
35+
return Math.max(robWithFirstHouse, robWithoutFirstHouse);
36+
}

0 commit comments

Comments
ย (0)