leetcode House Robber

快来打我* 2022-08-01 11:08 210阅读 0赞

题目

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.

题目来源:https://leetcode.com/problems/house-robber/

分析

动态规划,一维辅助数组dp。dp[i]表示从第i个元素开始往右,所能抢劫到的最大财富值(抢劫了第i个)。从右往左遍历,dp[i] = nums[i] + max(dp[i+2], dp[i+3]…dp[len-1])。可以设置一个辅助变量,维护自dp[i+2]往右的最大值,省得每次都求了。
还可以优化一下空间,我觉得可以不用一维辅助数组,用三个变量就行了。

代码

  1. class Solution {
  2. public:
  3. int rob(vector<int>& nums) {
  4. int size = nums.size();
  5. if(size == 0)
  6. return 0;
  7. vector<int> dp(size + 1, 0);
  8. dp[size-1] = nums[size-1];
  9. int ans = dp[size - 1];
  10. int max_next = 0;
  11. for(int i = size - 2; i >= 0; i--){
  12. dp[i] = nums[i] + max_next;
  13. ans = max(ans, dp[i]);
  14. max_next = max(dp[i+1], max_next);
  15. }
  16. return ans;
  17. }
  18. };

发表评论

表情:
评论列表 (有 0 条评论,210人围观)

还没有评论,来说两句吧...

相关阅读

    相关 [LeetCode] House Robber 打家劫舍||

    你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系

    相关 [LeetCode] House Robber 打家劫舍

    你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自