-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
213 House Robber II.swift
47 lines (38 loc) 路 1.23 KB
/
213 House Robber II.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//
// 213 House Robber II.swift
// LeetCode-Solutions
//
// Created by Aleksandar Dinic on 14/10/2020.
// Copyright 漏 2020 Aleksandar Dinic. All rights reserved.
//
import Foundation
/// Source: https://leetcode.com/problems/house-robber-ii/
class Solution {
/// Determines the maximum amount of money you can rob tonight without alerting the
/// police.
///
/// - Parameter nums: A list of non-negative integers representing the amount of money
/// of each house.
/// - Returns: The maximum amount of money you can rob.
///
/// - Complexity:
/// - time: O(n), where n is the length of the `nums`.
/// - space: O(1), only constant space is used.
func rob(_ nums: [Int]) -> Int {
guard !nums.isEmpty else { return 0 }
guard nums.count > 1 else { return nums[0] }
let ans1 = rob(nums, start: 0, end: nums.count - 1)
let ans2 = rob(nums, start: 1, end: nums.count)
return max(ans1, ans2)
}
private func rob(_ nums: [Int], start: Int, end: Int) -> Int {
var pre = 0
var cur = 0
for i in start..<end {
let tmp = cur
cur = max(cur, pre + nums[i])
pre = tmp
}
return cur
}
}