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

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

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 arearranged 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.

Credits:

Special thanks to  for adding this problem and creating all test cases.

 

LeetCode这是一天一道题的节奏吗?这道题就是在上一题的基础上加了一个条件,变成了环,所以如果抢了第一家,就不能抢最后一家。所以我们可以分别计算抢了从第二家到最后一家与抢从第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。

1 class Solution { 2 public: 3     int rob(vector
&num) { 4 if (num.size() == 0) return 0; 5 if (num.size() == 1) return num[0]; 6 vector
dp(num.size()); 7 //抢第一家到倒数第二家的最大值 8 dp[0] = num[0]; 9 for (int i = 1; i < num.size() - 1; ++i)10 dp[i] = max(dp[i-1], (i == 1 ? 0 : dp[i-2]) + num[i]);11 int res = dp[num.size()-2];12 //抢第二家到最后一家的最大值13 dp[1] = num[1];14 for (int i = 2; i < num.size() ; ++i)15 dp[i] = max(dp[i-1], (i == 2 ? 0 : dp[i-2]) + num[i]);16 //返回两者较大的一个 17 return max(res, dp[num.size()-1]);18 }19 };

 

转载于:https://www.cnblogs.com/easonliu/p/4516557.html

你可能感兴趣的文章
python高效读取文件、文件改写
查看>>
gulp
查看>>
pgsql查询优化之模糊查询
查看>>
[转]-Gradle使用手册(三):构建任务
查看>>
ExtJS下拉树
查看>>
android 调用系统相机录像并保存
查看>>
BW系统表的命名规则
查看>>
Asp.Net在IE10下出现_doPostBack未定义的解决办法 LinkButton
查看>>
《CLR via C#》Part2之Chapter5 基元类型、引用类型和值类型(一)
查看>>
1-9 RHEL7-文件权限管理
查看>>
apache服务器安装
查看>>
Search a 2D Matrix
查看>>
文件解析漏洞
查看>>
弹性成像的一些术语
查看>>
作业2
查看>>
vim 笔记
查看>>
MySQL的基本使用命令
查看>>
output 参数在存储过程中的用法
查看>>
大数加法和乘法(高精度)
查看>>
利用SynchronizationContext.Current在线程间同步上下文
查看>>