Skip to content

Commit c3e01dd

Browse files
committedMar 14, 2025··
solve 3
1 parent 05a17dc commit c3e01dd

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
 

‎house-robber-ii/pmjuu.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'''
2+
시간 복잡도: O(n)
3+
공간 복잡도: O(n)
4+
'''
5+
from typing import List
6+
7+
class Solution:
8+
def rob(self, nums: List[int]) -> int:
9+
n = len(nums)
10+
if n == 1:
11+
return nums[0]
12+
if n == 2:
13+
return max(nums[0], nums[1])
14+
15+
dp_first = [0] * n
16+
dp_second = [0] * n
17+
18+
dp_first[0], dp_first[1] = nums[0], max(nums[0], nums[1])
19+
dp_second[1], dp_second[2] = nums[1], max(nums[1], nums[2])
20+
21+
for i in range(2, n):
22+
dp_first[i] = max(dp_first[i - 1], dp_first[i - 2] + nums[i])
23+
dp_second[i] = max(dp_second[i - 1], dp_second[i - 2] + nums[i])
24+
25+
return max(dp_first[-2], dp_second[-1])

0 commit comments

Comments
 (0)
Please sign in to comment.