Description
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.
Examples
Example 1:
Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
Example 2:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 3:
Input: nums = [1,2,3]
Output: 3
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
思路
这个和198很像,只是将街区做成了循环。
那么就可以继续将这个问题分成两类,然后取最优解
- 我抢劫第一个社区 —— 我不可以抢劫最后一个社区, g ( t ) g(t) g(t) 的计算只能到 g ( n − 2 ) g(n-2) g(n−2)
- 我不抢劫第一个社区 —— 我可以抢劫最后一个社区, g ( t ) g(t) g(t) 的计算可以到 g ( n − 1 ) g(n-1) g(n−1)
ok,那状态转移方程其实是没有改变的,依旧是
g
(
t
)
=
max
(
g
(
t
−
1
)
,
f
(
t
)
+
g
(
t
−
2
)
)
g(t)=\max({g(t-1),f(t)+g(t-2)})
g(t)=max(g(t−1),f(t)+g(t−2))
初始化的时候就要分两种了,当然无论哪种,都只要初始化前两个
-
抢劫第一个社区。这里的 g ( 1 ) g(1) g(1) 设置为 f ( 0 ) f(0) f(0) 是因为我必抢劫第一个社区,那第二个我肯定抢不到,就不用算了
g ( 0 ) = f ( 0 ) g ( 1 ) = f ( 0 ) \begin{aligned} g(0) &= f(0)\\ g(1) &=f(0) \end{aligned} g(0)g(1)=f(0)=f(0) -
不抢劫第一个社区。那这里直接就把 g ( 1 ) g(1) g(1) 作为第一个社区就可以啦,后面不变
g ( 1 ) = f ( 1 ) g ( 2 ) = max ( f ( 1 ) , f ( 2 ) ) \begin{aligned} g(1) &= f(1)\\ g(2) &=\max({f(1), f(2)}) \end{aligned} g(1)g(2)=f(1)=max(f(1),f(2))
代码
class Solution {
public int rob(int[] nums) {
if(nums.length == 1)
return nums[0];
if(nums.length == 2)
return Math.max(nums[0], nums[1]);
if(nums.length == 3)
return Math.max(nums[0], Math.max(nums[1], nums[2]));
int answer[] = new int[nums.length];
answer[0] = nums[0];
answer[1] = nums[0];
for(int i = 2; i < nums.length - 1; i++){
answer[i] = Math.max(answer[i - 2] + nums[i], answer[i - 1]);
}
int max = answer[nums.length - 2];
answer[0] = Integer.MIN_VALUE;
answer[1] = nums[1];
answer[2] = Math.max(nums[1], nums[2]);
for(int i = 3; i < nums.length; i++){
answer[i] = Math.max(answer[i - 2] + nums[i], answer[i - 1]);
}
return Math.max(max, answer[nums.length - 1]);
}
}