House Robber

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 HouseRobber {

    public static void main(String[] args) {
        int[] money = {12,23,5,2,434,57,4,767,4,2};
        int maximum = houseRobber(money);
        System.out.println(maximum);
    }

    private static int houseRobber(int[] num) {
        if (0 == num.length) {
            return 0;
        }
        else if (1 == num.length) {
            return num[0];
        }
        else {
            num[1] = Math.max(num[0], num[1]);
            for (int i = 2; i < num.length; i++) {
                num[i] = Math.max(num[i-1], num[i-2] + num[i]); //这里没有想到
            }
        }
        return num[num.length-1];
    }

}

 

  

posted @ 2015-10-12 23:58  木易·月  阅读(173)  评论(0编辑  收藏  举报