213. House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system 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.

动态规划,和普通的动态规划不同的是这道题是首尾相连的。
因此分两种情况讨论——如果选择了头,就不选择尾。反之亦然。
建立两个动态规划表,分别选择第一个和第二个数字作为第一次抢劫的目标。
前一个最多抢劫到倒数第一个房子,后一个最多抢劫到最后一个房子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int rob(int[] nums) {
if(nums.length == 1) return nums[0];

int max = 0;
int[] dp = new int[nums.length+1];
int[] dp2 = new int[nums.length+1];
dp[1] = nums[0];

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

dp2[2] = nums[1];

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

return Math.max(dp[dp.length-2], dp2[dp2.length-1]);
}
}
Author

Xander

Posted on

2022-04-26

Updated on

2022-04-26

Licensed under

Comments