[LeetCode] House Robber

ゝ一世哀愁。 2022-08-05 01:00 197阅读 0赞

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.

思路:
1、条件:不能同时获取相邻的金钱
2、动态规划:当前节点的金钱数量等于当前的金额加上前面的金额最大值
3、最后遍历一次求出最大值即为结果

想到一种先排序,把下标记录下来,然后从后往前遍历,将下标差不为1的相加,wrong answer ,后面才想到用动态规划,看来动态规划还是不太熟

  1. public class Solution {
  2. public int rob(int[] nums) {
  3. if(nums.length == 2) return Math.max(nums[0], nums[1]) ;
  4. if(nums.length == 1) return nums[0] ;
  5. if(nums.length == 0) return 0 ;
  6. int[] indexs = new int[nums.length] ;
  7. for(int i = 0; i < nums.length; i ++){
  8. indexs[i] = nums[i] ;
  9. }
  10. int max = nums[0] ;
  11. for(int i = 2; i < nums.length; i ++){
  12. indexs[i] = indexs[i] + max ;
  13. max = Math.max(max, indexs[i - 1]) ;
  14. }
  15. int res = indexs[0] ;
  16. for(int i = 1; i < indexs.length; i ++){
  17. if(indexs[i] > res) res = indexs[i] ;
  18. }
  19. return res;
  20. }
  21. }

发表评论

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

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

相关阅读

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

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

    相关 [LeetCode] House Robber 打家劫舍

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