[leetCode] 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 Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) return 0;

        int[] res = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            int n1 = i - 2 >= 0 ? res[i-2] : 0;
            int n2 = i - 3 >= 0 ? res[i-3] : 0;
            n1 = Math.max(n1, n2);
            res[i] = n1 + nums[i];
        }

        int r;
        if (nums.length == 1) return res[0];
        r = Math.max(res[res.length-2], res[res.length-1]);
        return r;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章