Skip to content

feat: add swift implementation to lcof2 problem: No.090 #3476

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
Loading