House Robberm
2015-12-14 00:14
323 查看
题目:
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.
下面是开始自己写的代码,很挫。。
主要是自己开始没搞明白因为都是non-negative integers,所以随着往后遍历,其实最大的和一直都在倒数第一或者倒数第二的位置(因为倒数第三的位置求得的和加上倒数第一的数可能会小于倒数第二的位置的和),所以只要用两个变量来存我们最终要的最大的和就行了,具体代码如下:
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.
下面是开始自己写的代码,很挫。。
public class Solution { public int rob(int[] nums) { if (nums == null || nums.length == 0) { return 0; } if (nums.length == 1) { return nums[0]; } int max = 0; int[] a = new int[nums.length]; a[0] = nums[0]; a[1] = nums[0] > nums[1] ? nums[0] : nums[1]; max = a[1]; for (int i = 2;i < nums.length;i++) { for (int j = 0;j < i-1;j++) { if (a[i] < a[j] + nums[i]) { a[i] = a[j] + nums[i]; if (a[i] > max) { max = a[i]; } } } } return max; } }
主要是自己开始没搞明白因为都是non-negative integers,所以随着往后遍历,其实最大的和一直都在倒数第一或者倒数第二的位置(因为倒数第三的位置求得的和加上倒数第一的数可能会小于倒数第二的位置的和),所以只要用两个变量来存我们最终要的最大的和就行了,具体代码如下:
public class Solution { public int rob(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int a = 0,b = 0; for (int i = 0;i < nums.length;i++) { if (i % 2 == 0) { a = Math.max(a + nums[i],b); } else { b = Math.max(b + nums[i],a); } } return Math.max(a,b); } }
相关文章推荐
- MyBatis实战系列之(2)
- 使用BitmapFactory.Options进行图片的尺寸压缩实现节约内存
- 键盘控制DIV移动
- Android动态显示和隐藏状态栏
- HDOJ--1000
- 分布式版本控制系统----GIT的使用(三)
- 跟随鼠标的DIV和一连串跟随鼠标的DIV
- C# 我理解的接口、抽象类、以及事件
- 基于Python使用CloudSight API实现简单的图像识别(image Recognition)
- Linux指令记录
- MyBatis实战系列之(1)
- iOS 设置视图半透明而子控件不透明
- html5 表格使用基础
- Bios工程师手边事—HDA Audio
- html空格小结
- 单源最短路径-spfa算法
- windows10+iis7+php+mysql 配置
- Java正则表达式学习教程
- Java正则表达式入门学习
- php类中的$this,static,final,const,self这几个关键字使用方法