LeetCode //C - 198. House Robber

198. 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

From: LeetCode

Link: 198. House Robber


Solution:

Ideas:
  • We handle base cases where the size of nums is 0 or 1.
  • We create an array dp to store the maximum amount that can be robbed up to each house.
  • The first element of dp is the amount in the first house, and the second element is the maximum of the first two houses.
  • For each subsequent house i, we calculate the maximum amount that can be robbed by comparing:
    • The amount robbed by robbing the current house i (which is nums[i] + dp[i - 2]) and not robbing the immediate previous house.
    • The amount robbed by not robbing the current house (which is dp[i - 1]).
  • Finally, we return the last element of the dp array, which represents the maximum amount that can be robbed from the entire street.
Code:
c 复制代码
int rob(int* nums, int numsSize) {
    if (numsSize == 0) return 0;
    if (numsSize == 1) return nums[0];

    int dp[numsSize];
    dp[0] = nums[0];
    dp[1] = nums[1] > nums[0] ? nums[1] : nums[0];

    for (int i = 2; i < numsSize; i++) {
        dp[i] = (nums[i] + dp[i - 2]) > dp[i - 1] ? nums[i] + dp[i - 2] : dp[i - 1];
    }

    return dp[numsSize - 1];
}
相关推荐
丶Darling.29 分钟前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
思茂信息1 小时前
CST软件对OPERA&CST软件联合仿真汽车无线充电站对人体的影响
c语言·开发语言·人工智能·matlab·汽车·软件构建
L_cl1 小时前
【Python 算法零基础 3.递推】
算法
川川菜鸟1 小时前
2025长三角数学建模C题完整思路
c语言·开发语言·数学建模
int型码农2 小时前
数据结构第七章(四)-B树和B+树
数据结构·b树·算法·b+树
云海听雷2 小时前
C语言中字符串函数的详细讲解
c语言·笔记·学习
先做个垃圾出来………2 小时前
汉明距离(Hamming Distance)
开发语言·python·算法
C++ 老炮儿的技术栈2 小时前
自定义CString类与MFC CString类接口对比
c语言·c++·windows·qt·mfc
人类恶.3 小时前
C 语言学习笔记(数组)
c语言·笔记·学习
小羊在奋斗3 小时前
【LeetCode 热题 100】二叉树的最大深度 / 翻转二叉树 / 二叉树的直径 / 验证二叉搜索树
算法·leetcode·职场和发展