Skip to content

Commit d3768f5

Browse files
authored
feat: add swift implementation to lcof2 problem: No.090 (#3476)
1 parent 1fdf6c1 commit d3768f5

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lcof2/剑指 Offer II 090. 环形房屋偷盗/README.md

+24
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,30 @@ impl Solution {
192192
}
193193
```
194194

195+
#### Swift
196+
197+
```swift
198+
class Solution {
199+
func rob(_ nums: [Int]) -> Int {
200+
let n = nums.count
201+
if n == 1 {
202+
return nums[0]
203+
}
204+
return max(rob(nums, 0, n - 2), rob(nums, 1, n - 1))
205+
}
206+
207+
private func rob(_ nums: [Int], _ l: Int, _ r: Int) -> Int {
208+
var f = 0, g = 0
209+
for i in l...r {
210+
let temp = max(f, g)
211+
g = f + nums[i]
212+
f = temp
213+
}
214+
return max(f, g)
215+
}
216+
}
217+
```
218+
195219
<!-- tabs:end -->
196220

197221
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
func rob(_ nums: [Int]) -> Int {
3+
let n = nums.count
4+
if n == 1 {
5+
return nums[0]
6+
}
7+
return max(rob(nums, 0, n - 2), rob(nums, 1, n - 1))
8+
}
9+
10+
private func rob(_ nums: [Int], _ l: Int, _ r: Int) -> Int {
11+
var f = 0, g = 0
12+
for i in l...r {
13+
let temp = max(f, g)
14+
g = f + nums[i]
15+
f = temp
16+
}
17+
return max(f, g)
18+
}
19+
}

0 commit comments

Comments
 (0)