LeetCode House Robber II
2015-07-09 14:52
417 查看
Description:
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a
circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
Solution:
固定第一个点, 然后从第二个点开始dp即可。
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a
circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
Solution:
固定第一个点, 然后从第二个点开始dp即可。
import java.util.*; public class Solution { public int rob(int[] nums) { int n = nums.length; if (n == 0) return 0; int dp[][] = new int [2]; if (n == 1) return nums[0]; dp[0][0] = 0; dp[0][1] = nums[0]; dp[1][0] = 0; dp[1][1] = nums[1]; for (int i = 2; i < n; i++) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]); dp[i][1] = dp[i - 1][0] + nums[i]; } int max = Math.max(dp[n - 1][0], dp[n - 1][1]); dp[1][0] = nums[0]; dp[1][1] = nums[1]; for (int i = 2; i < n; i++) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]); dp[i][1] = dp[i - 1][0] + nums[i]; } max = Math.max(max, dp[n - 1][0]); return max; } }
相关文章推荐
- 基于反射实现自动化restful开发
- 我不同意你,这是您的支持
- 面向对象编程,走迷宫
- swift方法使用
- NGX负载均衡策略
- AD认证
- 单机tcp并发连接
- Ubuntu 12.04安装python3.4
- java架构师之路:JAVA程序员必看的15本书的电子版下载地址
- VisualSVN Server仓库迁移到Linux(包含所有版本, 权限,用户信息)
- 第1章 Lua基础
- AD认证
- Struts2 上传文件方法
- struts2继承ServletRequestAware获取request为null的问题
- SCCM 2012安装教程(Part2)
- 《统计学习方法》笔记(十一)--SMO
- UML类图
- UIButton UIEdgeInsetsMake
- LintCode 丑数
- hdu 4389 X mod f(x) 数位dp