198打家劫舍

import sys
from typing import List

# sys.setrecursionlimit(2000) # 这行通常用于递归解法,对于这个迭代DP解法不是必需的

class Solution:
    """
    解决 LeetCode 198. 打家劫舍 问题的类
    """
    def rob(self, nums: List[int]) -> int:
        """
        计算在不触动警报的情况下,能偷窃到的最高金额。

        Args:
            nums: 一个列表,代表每个房屋存放的非负整数金额。

        Returns:
            可以偷窃到的最高总金额。
        """
        n = len(nums)

        # 处理边界情况 / Edge Cases:
        if n == 0:  # 如果没有房屋
            return 0
        if n == 1:  # 如果只有一个房屋
            return nums[0]

        # 创建 DP 数组 (Create DP array)
        # dp[i] 将存储考虑前 i 间房屋(即 nums 数组中下标 0 到 i-1)时能偷到的最大金额。
        # 数组大小为 n+1 以便索引 i 能直接表示考虑的房屋数量。
        # dp[i] = maximum amount of money that can be robbed from the first i houses (indices 0 to i-1 in nums).
        # Size is n+1 so index i directly represents the number of houses considered.
        dp = [0] * (n + 1)

        # 初始化基础情况 / Initialize Base Cases:
        dp[0] = 0           # 考虑前 0 间房,最大金额为 0 (Max money from 0 houses is 0)
        dp[1] = nums[0]     # 考虑前 1 间房 (nums[0]),最大金额为 nums[0] (Max money from the first house is its value)

        # 动态规划递推 / Dynamic Programming Recurrence:
        # 从 i = 2 开始,计算考虑前 i 间房的最大金额
        # Start from i = 2, calculate max money considering first i houses
        for i in range(2, n + 1):
            # 对于第 i 间房屋(在 nums 中的下标是 i-1),有两种选择:
            # For the i-th house (index i-1 in nums), there are two choices:

            # 1. 不偷第 i 间房 (nums[i-1]):
            #    此时能获得的最大金额等于考虑前 i-1 间房的最大金额。
            #    Don't rob house i-1: Max money is the same as the max from the first i-1 houses.
            option1 = dp[i-1]

            # 2. 偷第 i 间房 (nums[i-1]):
            #    此时不能偷第 i-1 间房 (nums[i-2])。
            #    能获得的最大金额等于第 i 间房的金额加上考虑前 i-2 间房的最大金额。
            #    Rob house i-1: Cannot rob house i-2.
            #    Max money is nums[i-1] + max money from the first i-2 houses.
            option2 = dp[i-2] + nums[i-1]

            # dp[i] 取这两种选择中的较大值
            # dp[i] takes the maximum of these two options
            dp[i] = max(option1, option2)

        # 返回结果 / Return Result:
        # dp[n] 存储了考虑所有 n 间房屋后的最大金额
        # dp[n] stores the maximum amount after considering all n houses.
        # 在 Python 中,dp[-1] 是访问列表最后一个元素的便捷方式,它等价于 dp[n]。
        # In Python, dp[-1] is a convenient way to access the last element, equivalent to dp[n].
        return dp[-1]

# 示例用法 (Example Usage)
# solution = Solution()
# print(solution.rob([1, 2, 3, 1]))  # Output: 4
# print(solution.rob([2, 7, 9, 3, 1])) # Output: 12

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值