2015年8月29日星期六

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[] maxRob = new int[nums.length];
        int[] maxNoRob = new int[nums.length];
        maxRob[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int n = nums[i];
            maxRob[i] = maxNoRob[i - 1] + n;
         
            maxNoRob[i] = Math.max(maxNoRob[i - 1], maxRob[i - 1]);
        }
        return Math.max(maxNoRob[nums.length - 1], maxRob[nums.length - 1]);
    }
}
==============

public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int[] maxRob = new int[nums.length + 1];
        maxRob[0] = 0;
        maxRob[1] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int n = nums[i];
            maxRob[i + 1] = Math.max(maxRob[i - 1] + n, maxRob[i]);
        }
        return maxRob[nums.length];
    }
}

没有评论:

发表评论