博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: House Robber II
阅读量:5361 次
发布时间:2019-06-15

本文共 2004 字,大约阅读时间需要 6 分钟。

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.

Analysis: Now that the houses are arranged in a circle with the first house being the neighbor for the last one. Robbing the first house means the last one cannot be robbed, vise versa. So totally we have three choices here, 

1. rob the first and don't rob the last house

2. rob the last one and don't rob the first house.

3. neither rob the first one nor the last one

What we do is we take off the first house and last one respectively. Calculate the maximum money we can rob by robbing the rest of the houses. We get two maximum value. Choose the larger one. These two maximum value will cover those three cases above.

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

 

转载于:https://www.cnblogs.com/EdwardLiu/p/5053679.html

你可能感兴趣的文章
随手练——HDU 5015 矩阵快速幂
查看>>
Java变量类型,实例变量 与局部变量 静态变量
查看>>
Python环境搭建(安装、验证与卸载)
查看>>
一个.NET通用JSON解析/构建类的实现(c#)
查看>>
如何辨别一个程序员的水平高低?是靠发量吗?
查看>>
linux的子进程调用exec( )系列函数
查看>>
MySQLdb & pymsql
查看>>
zju 2744 回文字符 hdu 1544
查看>>
【luogu P2298 Mzc和男家丁的游戏】 题解
查看>>
前端笔记-bom
查看>>
上海淮海中路上苹果旗舰店门口欲砸一台IMAC电脑维权
查看>>
Google透露Android Market恶意程序扫描服务
查看>>
给mysql数据库字段值拼接前缀或后缀。 concat()函数
查看>>
迷宫问题
查看>>
【FZSZ2017暑假提高组Day9】猜数游戏(number)
查看>>
泛型子类_属性类型_重写方法类型
查看>>
练习10-1 使用递归函数计算1到n之和(10 分
查看>>
Oracle MySQL yaSSL 不明细节缓冲区溢出漏洞2
查看>>
Code Snippet
查看>>
zoj 1232 Adventure of Super Mario
查看>>