House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums
representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 400
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
if n <= 2 :
return max(nums)
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, n) :
dp[i] = max(dp[i-2] + nums[i], dp[i-1])
return dp[-1]
DP 베이직? 이라고 생각하면 편한 문제라고 생각한다. 옛날에 푼 적 있었는데 또 풀어보니 새롭다.
처음에는 n == 1, 2를 따로 구분해줬었는데, 굳이 그럴 필요 없을 거 같아서 n <= 2 로 부여해줬다. 나중에 최적화 쪽에 대해서도 얘기해보는 것도 나쁘지 않을듯? 크게 다를까 싶긴 하다.
저런 가지치기 말고 패딩을 통하여 ([0] 을 몇개 넣는다든지) 코드를 더 생략할 수 있지 않을까? 라는 생각도 든다.
문제는 바로 옆의 집은 접근이 불가능하고 하나씩 건너뛰며 집을 들릴 수 있는 점이 특징인 문제이다. 나중에 그림으로도 표현할 수 있으면 좋은 풀이를 확인할 수 있을 것이다.
'알고리즘 스터디' 카테고리의 다른 글
[Leetcode/파이썬] 155. Min Stack (1) | 2025.08.31 |
---|---|
[Leetcode/파이썬] 433. Minimum Genetic Mutation (2) | 2025.08.29 |
[Leetcode/파이썬] 56. Merge Intervals (0) | 2025.08.14 |
[Leetcode/파이썬] 49. Group Anagrams (3) | 2025.08.13 |
[Leetcode/파이썬] 228.Summary Ranges (0) | 2025.08.13 |