diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/README.md" index cbdde236ac876..a5078e70925c3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/README.md" @@ -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) + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.swift" new file mode 100644 index 0000000000000..bdfbc1be01907 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/Solution.swift" @@ -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) + } +} \ No newline at end of file