Skip to content

Commit 5762ba2

Browse files
committed
Add solution for House Robber
1 parent a5a0744 commit 5762ba2

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

โ€Žhouse-robber/gcount85.pyโ€Ž

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
# Intuition
3+
DP๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
4+
5+
# Approach
6+
ํŠน์ • ์ง‘์˜ ์ตœ๋Œ€ money ๊ฐ’ = max(์ „์ „์ง‘์„ ํ„ธ์—ˆ์„ ๊ฒฝ์šฐ์˜ ์ตœ๋Œ“๊ฐ’ + ํ˜„์žฌ ์ง‘์˜ money ๊ฐ’, ์ด์ „ ์ง‘์„ ํ„ด ๊ฒฝ์šฐ์˜ ์ตœ๋Œ“๊ฐ’)
7+
8+
# Complexity
9+
- Time complexity: O(N)
10+
- Space complexity: O(N)
11+
"""
12+
13+
14+
class Solution:
15+
def rob(self, nums: List[int]) -> int:
16+
n = len(nums)
17+
dp = [0] * n # O(N)
18+
19+
if n == 1:
20+
return nums[0]
21+
22+
dp[0] = nums[0]
23+
dp[1] = max(dp[0], nums[1])
24+
for house in range(2, n): # O(N)
25+
dp[house] = max(dp[house - 1], dp[house - 2] + nums[house])
26+
27+
return dp[n - 1]

0 commit comments

Comments
ย (0)