LeetCode 213. House Robber II
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 213. House Robber II相关的知识,希望对你有一定的参考价值。
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++:
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); } };
以上是关于LeetCode 213. House Robber II的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 198, 213 House Robber
[动态规划] leetcode 213 House Robber II
leetCode 213. House Robber II | Medium | Dynamic Programming