码迷,mamicode.com
首页 > 其他好文 > 详细

House Robber I && II

时间:2015-05-27 06:17:38      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

I

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.

 

public class Solution {
    public int rob(int[] num) {
 // https://leetcode.com/discuss/30020/java-o-n-solution-space-o-1 不是很理解
    int prevNo = 0;
    int prevYes = 0;
    for (int n : num) {
        int temp = prevNo;
        prevNo = Math.max(prevNo, prevYes); // here prevNo is the next loop‘s prevNo
        prevYes = n + temp;                 // next loop‘s prevYes
    }
    return Math.max(prevNo, prevYes);

    }
}

II

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.

 

思路摘抄  http://blog.csdn.net/xudli/article/details/45886721

House Robber I的升级版. 因为第一个element 和最后一个element不能同时出现. 则分两次call House Robber I. case 1: 不包括最后一个element. case 2: 不包括第一个element.

两者的最大值即为全局最大值

public class Solution {
    public int rob(int[] nums) {
        if(nums==null|| nums.length==0) return 0;
        if(nums.length<3) return Math.max(nums[0],nums[nums.length-1]);
        int pn=0, py= 0, r1=0, r2=0;
        for(int i=0;i<nums.length-1;i++){
            int tmp = pn;
            pn = Math.max(pn,py);
            py=nums[i]+tmp;
        }
        r1 = Math.max(pn,py);
        pn=0;
        py=0;
        for(int i=1;i<nums.length;i++){
            int tmp = pn;
            pn = Math.max(pn,py);
            py=nums[i]+tmp;
        }
        r2 = Math.max(pn,py);
        return Math.max(r1,r2);
    }
}

 

House Robber I && II

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4532258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!