leetcode|leetcode_House Robber II
描述:
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.
思路:
1.和House Robber的思路类似,只是本题中房子是首尾相连的,也就是说第一个房子和最后一个房子不能都被盗,否则,触发警报,小偷被抓
2.在House Robber的基础上,a:如果从第一座房子开始偷窃,那么最后一个房子肯定不能被偷;b:如果从第二座房子偷窃,那么最后一个房子可以被偷,分别对这两种情况进行计算即可。
代码:
public int rob(int[] nums) {
if(nums==null)
return 0;
int len=nums.length;
int maxProfit=0;
if(len==0)
return 0;
else if(len==1)
return nums[0];
else if(len==2)
return Math.max(nums[0],nums[1]);
else
{
int tempMaxProfit1=getMaxProfit(nums, 0, nums.length-2);
int tempMaxProfit2=getMaxProfit(nums, 1, nums.length-1);
maxProfit=Math.max(tempMaxProfit1, tempMaxProfit2);
}
return maxProfit;
}
public int getMaxProfit(int nums[],int start,int end)
{
int maxProfit1=nums[start];
//用maxProfit1、maxProfit2来避免用数组来存储临时变量
int maxProfit2=Math.max(nums[start],nums[start+1]);
int maxProfit=Math.max(maxProfit1, maxProfit2);
for(int i=start+2;
i<=end;
i++)
{
maxProfit=Math.max(maxProfit2,maxProfit1+nums[i]);
maxProfit1=maxProfit2;
maxProfit2=maxProfit;
}
return maxProfit;
}
【leetcode|leetcode_House Robber II】
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- Leetcode|Leetcode No.198打家劫舍
- [leetcode数组系列]1两数之和
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路
- LeetCode|LeetCode 876. 链表的中间结点