198. 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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

 

Hide Tags
  Dynamic Programming  

链接:  http://leetcode.com/problems/house-robber/

题解:

一维DP,  当前最大值相当于Math.max(nums[i - 1],nums[i] + nums[i - 2]),处理一下边界情况就可以了。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public int rob(int[] nums) {

        if(nums == null || nums.length == 0)

            return 0;

            

        for(int i = 0; i < nums.length; i++){

            int temp1 = i - 1 < 0 ? 0 : nums[i - 1];

            int temp2 = i - 2 < 0 ? 0 : nums[i - 2];

            nums[i] = Math.max(temp1, nums[i] + temp2);

        }

        

        return nums[nums.length - 1];

    }

}

 

测试:

Reference:

你可能感兴趣的:(r)