【Leetcode】House Robber

来源:互联网 发布:js 汉字长度 编辑:程序博客网 时间:2024/06/06 03:52

题目链接: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.

思路:

用n数组表示到当前元素为止的最大值。则n[i]只跟n[i-2]和n[i-1]有关,当n[i-1]大于n[i-2]+nums[i]的时候可以放弃抢劫nums[i],因为抢了还不如不抢,且抢了i-2、i-1的情况下都可以抢劫i+1。

算法:

public int rob(int[] nums) {      if(nums.length==0)          return 0;      if(nums.length==1)          return nums[0];      if(nums.length==2)          return Math.max(nums[0], nums[1]);      int n[] = new int[nums.length];      n[0] = nums[0];      n[1]=Math.max(nums[0], nums[1]);      for(int i=2;i<nums.length;i++){          n[i] = Math.max(nums[i]+n[i-2],n[i-1]);      }      return n[nums.length-1];  }  


1 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 ssni 输入梯形上底下底高,输出面积 python语言,输入梯形上底下底高输出面积 网易产品 https://www.csdndoc.com/blog/390696 https://www.cocoacontrols.com 风之教堂 黄色网站 AV网站 439973416 فیلترشکن WS_CLIPCHILDREN设置键在哪里 数据结构(严蔚敏李冬梅)课后答案 ipz809 一个字包含的二进制位数 linux面试 【题目2】设计一个结构体类型,包含姓名、出生日期。其中出生日期又包含年、月、日三部分信息。输入n个好 【题目2】设计一个结构体类型,包含姓名、出生日期。其中出生日期又包含年、月、日三部分信息。输入n个好 结构体比较好友中年纪最小的 matlab三维矩阵可视化 使QQ崩溃 scanIP 按照规定,在高速公路上行使的机动车,达到或超出本车道限速的10%则处200元罚款;若达到或超出50% c语言输入三个数字 c语言如何输入三个数求平均值 c语言如何输入三个数求和 C语言为什么只录入了第一个数字 输入多个数字 c语言scanf只有第一个数字 scanf三个整数 double double类型 www和http 会计 日记账 myamnatfound IntroductiontoIoT IntroductiontoIoT 使用哪种类型的无线网络连接城市中的设备来创建城域网 傲世九重天绿帽版 节日