Skip to content

Commit

Permalink
feat: add swift implementation to lcof2 problem: No.090
Browse files Browse the repository at this point in the history
  • Loading branch information
klever34 committed Sep 3, 2024
1 parent 1fdf6c1 commit bb68b0b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lcof2/剑指 Offer II 090. 环形房屋偷盗/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,30 @@ impl Solution {
}
```

#### Swift

```swift
class Solution {
func rob(_ nums: [Int]) -> Int {
let n = nums.count
if n == 1 {
return nums[0]
}
return max(rob(nums, 0, n - 2), rob(nums, 1, n - 1))
}

private func rob(_ nums: [Int], _ l: Int, _ r: Int) -> Int {
var f = 0, g = 0
for i in l...r {
let temp = max(f, g)
g = f + nums[i]
f = temp
}
return max(f, g)
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
19 changes: 19 additions & 0 deletions lcof2/剑指 Offer II 090. 环形房屋偷盗/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution {
func rob(_ nums: [Int]) -> Int {
let n = nums.count
if n == 1 {
return nums[0]
}
return max(rob(nums, 0, n - 2), rob(nums, 1, n - 1))
}

private func rob(_ nums: [Int], _ l: Int, _ r: Int) -> Int {
var f = 0, g = 0
for i in l...r {
let temp = max(f, g)
g = f + nums[i]
f = temp
}
return max(f, g)
}
}

0 comments on commit bb68b0b

Please sign in to comment.