Leetcode-198. House Robber 打家劫舍 (DP)

题目

你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
链接:https://leetcode.com/problems/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 system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example:

Input: [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.

思路及代码

DP

  • ans:当前为止能得到的最多的钱
  • ans = max(num + temp, one)
    • num+temp:假设抢劫当天,则取两天前能得到的最多的钱+今天
    • one:前一天能得到的最多的钱
class Solution:
    def rob(self, nums: List[int]) -> int:
        one = 0
        two = 0
        for num in nums:
            temp = one
            one = two
            two = max(num + temp, one)
        return two

复杂度

T = O ( n ) O(n) O(n)
S = O ( 1 ) O(1) O(1)

你可能感兴趣的:(Leetcode,leetcode,算法,动态规划,python)