작심삼일

[LeetCode] 198 | House Robber | Python 본문

스터디/코테

[LeetCode] 198 | House Robber | Python

yun_s 2022. 12. 14. 09:30
728x90
반응형

문제 링크: https://leetcode.com/problems/house-robber/description/


문제

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.


조건

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

내 풀이

Dynamic Programming으로 푼다.

[n-1째 집을 털지 않고 n번째 집을 터는 것]이 [n-1번째 집을 터는 것]보다 이득이 클 때 n번째 집을 턴다.

이를 dp로 나타내면 다음과 같다.

dp[n] = max(dp[n-2]+nums[n], dp[n-1])


코드

class Solution:
    def rob(self, nums: List[int]) -> int:
        dp = [0, nums[0]]

        for idx, num in enumerate(nums[1:]):
            dp.append(max(dp[idx]+num, dp[idx+1]))

        return dp[-1]
 
728x90
반응형
Comments