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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

动态规划。
dp数组记录经过i个房子后可以获得的最大值。
dp[i+1]的值等于dp[i-1]加上现有房子的钱(抢这个房子)与dp[i]的值(不抢这个房子)中的较大值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int rob(int[] nums) {

int[] money = new int[nums.length+1];
money[0] = 0;
money[1] = nums[0];

for (int i = 1; i < nums.length; i++){
money[i+1] = Math.max(money[i-1]+nums[i],money[i]);

}

return money[nums.length];

}
}
Author

Xander

Posted on

2022-04-14

Updated on

2022-04-13

Licensed under

Comments