[Leetcode]House Robber II
来源:互联网 发布:淘宝遭遇职业打假人 编辑:程序博客网 时间:2024/06/03 18:54
House Robber II
Total Accepted: 18212 Total Submissions: 63419 Difficulty: Medium
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
遍历两次。
第一次假设不存在nums[len - 1],从1 ~ len - 2,得到一个最大值。
第二次假设不存在nums[0],从len - 2 ~ 1,得到一个最大值。
则真正的最优解肯定在这两个之中
class Solution {public: int rob(vector<int>& nums) { int len = nums.size(); if(!len) return 0; vector<int> get(len,0); vector<int> pop(len,0); get[0] = nums[0]; int res0 = nums[0]; for(int i = 1;i <= len - 2;++ i){ get[i] = max(pop[i - 1],i >= 2 ? get[i - 2] : 0) + nums[i]; pop[i] = max(pop[i - 1],get[i - 1]); res0 = max(res0,max(get[i],pop[i])); } int res1 = nums[len - 1]; fill(get.begin(),get.end(),0); fill(pop.begin(),pop.end(),0); get[len - 1] = nums[len - 1]; for(int i = len - 2;i >= 1;-- i){ get[i] = max(pop[i + 1],i + 2 <= len - 1 ? get[i + 2] : 0) + nums[i]; pop[i] = max(pop[i + 1],get[i + 1]); res1 = max(res1,max(get[i],pop[i])); } return max(res1,res0); }};
- LeetCode House Robber II
- [LeetCode] House Robber II
- [leetcode] House Robber II
- 【leetcode】House Robber II
- Leetcode: House Robber II
- leetcode House Robber II
- [leetcode] House Robber II
- [LeetCode]House Robber II
- leetcode--House Robber II
- leetcode House Robber II
- LeetCode House Robber II
- leetcode:House Robber II
- Leetcode: House Robber II
- House Robber II -- leetcode
- leetCode House Robber II
- [Leetcode]House Robber II
- Leetcode: House Robber II
- LeetCode House Robber II
- ADO.NET之Parameter属性
- swift字符串
- 头文件重复包含和变量重复定义
- ListView具有多种item布局
- Html5获取图片原始宽高
- [Leetcode]House Robber II
- Swift:可选类型的含义
- ElasticSearch学习5_一些国外优秀的elasticsearch使用案例
- caffe调用已生成的模型,测试(Linux)
- 杭电OJ 3190 (贪心)Stall Reservations
- 在vmware中用kdb调试linux内核和模块
- 安卓用websocket实现推送
- 14-1 UITableView综合-模态viewController、单例(LED,Neon)
- 【Modern OpenGL】前言