Przebudzenie w kawiarni: przełomowy moment w Zalipiu
Pewnego mroźnego poranka w kawiarni w Zalipiu 53-letnia Bogumiła doświadczyła szokującego olśnienia, które odmieniło jej życie. Zmęczenie, gromadzone latami, wybuchło nagle, zmuszając ją, by spojrzeła na siebie i swoją rodzinę zupełnie innymi oczami.
Mimo wieku Bogumiła czuła się młoda duchem. Po prostu nie miała czasu myśleć o starości. Kręciła się jak bąk w trybach codzienności, pracując na trzech etatach, by utrzymać rodzin# [213. House Robber II][1]
> 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 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**.
>
> **Example 1:**
>
> “`
> Input: [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: [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.
> “`
## 方法一:DP
题目描述:**所有房子排成环**,不能偷相邻的两个房子,求最大能偷的金额。
环状排列意味着第一个房子和最后一个房子中只能选择一个偷窃,因此可以把此环状排列房间问题约化为两个单排排列房间子问题:
* 在不偷窃第一个房子的情况下(即 `nums[1:len]`),最大金额是 $p_1$
* 在不偷窃最后一个房子的情况下(即 `nums[0:len-1]`),最大金额是 $p_2$
综合偷窃最大金额:$max(p1, p2)$
代码如下:
“`java
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int n = nums.length;
if (n == 1)
return nums[0];
return Math.max(rob(nums, 0, n-2), rob(nums, 1, n-1));
}
private int rob(int[] nums, int first, int last) {
int pre1 = 0, pre2 = 0;
for (int i = first; i <= last; i++) {
int temp = pre1;
pre1 = Math.max(pre1, pre2 + nums[i]);
pre2 = temp;
}
return pre1;
}
}
```
[1]: https://leetcode.com/problems/house-robber-ii/



