반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 198 | House Robber | Python 본문
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
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 520 | Detect Capital | Python (0) | 2023.01.02 |
---|---|
[LeetCode] 70 | Climbing Stairs | Python (0) | 2022.12.12 |
[LeetCode] 872 | Leaf-Similar Trees | Python (0) | 2022.12.08 |
[LeetCode] 876 | Middle of the Linked List | Python (0) | 2022.12.05 |
[LeetCode] 1704 | Determine if String Halves Are Alike | Python (0) | 2022.12.01 |
Comments