House Robber

题目地址:
https://leetcode.com/problems/house-robber/#/description

题目:
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.

解题思路:
这道题就是用dynamic programming,有可以抢劫和不可以抢劫两种。

代码:

public int rob(int[] nums) {
    int len = nums.length;
    int[][] dp = new int[len + 1][2];
    for(int i = 1; i <= len; i++){
        dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
        dp[i][1] = dp[i - 1][0] + nums[i - 1];
    }
    return Math.max(dp[len][0], dp[len][1]);
}

Comments

Popular Posts