LeetCode 213. House Robber II
2016-06-25 21:24
218 查看
Problem: https://leetcode.com/problems/house-robber-ii/
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.
Thought:
Uses the code in House-robber, chooce the larger one between num[0] to num[n - 2] and num[1] to num[n - 1]
Code C++:
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.
Thought:
Uses the code in House-robber, chooce the larger one between num[0] to num[n - 2] and num[1] to num[n - 1]
Code C++:
class Solution { public: int rob(vector<int>& nums) { if (nums.size()==0) return 0; else if (nums.size() == 1) return nums[0]; int n1 = 0,n2 = nums[0]; for (int i = 1; i < nums.size() - 1; i++) { int temp = n1; n1 = n2; n2 = max(temp + nums[i], n2); } int pre = n2; n1 = 0,n2 = nums[1]; for (int i = 2; i < nums.size(); i++) { int temp = n1; n1 = n2; n2 = max(temp + nums[i], n2); } int lat = n2; return max(pre,lat); } };
相关文章推荐
- 几个用Python实现的简单算法
- codeforces 685B Kay and Snowflake 树的重心
- Android 通用流行15类框架大全,你都知道吗?
- 记第一次打字测试
- 小白上手第二弹——浅析Context
- 事件处理
- 【JavaScript】DOM
- android 四大组件之Service(8) 通过信使进行远程通信
- soapui笔记7:断言2
- 因为我爱你,所以我不愿做那2分的缺憾
- 轻量级分布式 RPC 框架
- ContentProvider内容提供商的简单使用(上)
- ajax
- redhat enterprixe 5.0 NFS服务配置与管理
- 软件工程总结
- leetcode 343. Integer Break 解题报告
- Parse 控制面板
- 图像局部特征(四)--FAST-ER角点检测子
- soapui笔记6:断言1
- DOM