Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 4170af0

Browse files
authored
Create 213. House Robber II.md
1 parent 828ba48 commit 4170af0

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎213. House Robber II.md‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# 213. House Robber II
2+
3+
### 2020年07月31日
4+
5+
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**.
6+
7+
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**.
8+
9+
**Example 1:**
10+
11+
```
12+
Input: [2,3,2]
13+
Output: 3
14+
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
15+
because they are adjacent houses.
16+
```
17+
18+
**Example 2:**
19+
20+
```
21+
Input: [1,2,3,1]
22+
Output: 4
23+
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
24+
Total amount you can rob = 1 + 3 = 4.
25+
```
26+
27+
28+
29+
# Solution
30+
31+
```swift
32+
33+
class Solution {
34+
35+
private func robLine(start: Int, end: Int, nums: [Int]) -> Int {
36+
var cache = [Int: Int]()
37+
for i in start..<end {
38+
let x = end - i - 1 + start
39+
cache[x] = max(nums[x] + (cache[x + 2] ?? 0), cache[x + 1] ?? 0)
40+
}
41+
return cache[start] ?? 0
42+
}
43+
44+
func rob(_ nums: [Int]) -> Int {
45+
guard nums.count > 0 else {
46+
return 0
47+
}
48+
if nums.count / 2 == 0 {
49+
return robLine(start: 0, end: nums.count, nums: nums)
50+
} else {
51+
return max(robLine(start: 0, end: nums.count - 1, nums: nums), robLine(start: 1, end: nums.count, nums: nums))
52+
}
53+
}
54+
}
55+
56+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /