【Leetcode】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.

---

基于上一次写的house robber,其实这道题会比较有意思。我的思路是这道题的本质其实是,给了一个array,那么第一个element和最后一个element就不能连着,那么我们能不能分成两种array看?就是最后返回的这个抢劫的组合里,要么有第一个元素,要么有最后一个元素,反正不能同时有,那么我们就跟随上一道题的基础上,分别看nums[1:],nums[:-1]。

public class Solution {
    public int rob(int[] nums) {
        if(nums==null || nums.length<1)
            return 0;
        if(nums.length<2)
            return nums[0];
        if(nums.length<3)
            return Math.max(nums[0],nums[1]);
		int[] arr1;
		int[] arr2;
		arr1 = move(nums,0);
		arr2 = move(nums,nums.length-1);
		return Math.max(robMany(arr1), robMany(arr2));
    }
    private static int[] move(int[] nums, int index){
		ArrayList<Integer> list = new ArrayList<Integer>();
		for(int num : nums){
			list.add(num);
		}
		list.remove(index);
		int[] ans = new int[nums.length];
		for(int i=0;i<list.size();i++)
			ans[i]=list.get(i);
		return ans;
	}
	 public int robMany(int[] nums){

	        int max = nums[0];
	        int[] big = new int[nums.length];
	        big[0] = nums[0];
	        big[1] = nums[1];
	        for(int i=2;i<nums.length;i++){
	        	big[i] = nums[i] + max;
	        	if(big[i-1] > max)
	        		max = big[i-1];
	        }
	        return big[nums.length-1] > big[nums.length-2]?big[nums.length-1]:big[nums.length-2];
	 }
}
分享一个大神的解释:

https://leetcode.com/discuss/36544/simple-ac-solution-in-java-in-o-n-with-explanation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值