-
Notifications
You must be signed in to change notification settings - Fork 15
/
198_HouseRobber.swift
55 lines (50 loc) · 1.19 KB
/
198_HouseRobber.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
48
49
50
51
52
53
54
55
//
// 198_HouseRobber.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-09-15.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:198 House Robber
URL: https://leetcode.com/problems/house-robber/
Space: O(n)
Time: O(n)
*/
class HouseRobber_Solution {
func rob(_ nums: [Int]) -> Int {
guard nums.count > 0 else {
return 0
}
// NOTE: The maximum value by robbing current room.
var robCurrentRoom = Array(repeating: 0, count: nums.count)
for i in 0..<nums.count {
if i == 0 {
robCurrentRoom[i] = nums[0]
} else if i == 1 {
robCurrentRoom[i] = max(nums[0], nums[1])
} else {
robCurrentRoom[i] = max(robCurrentRoom[i - 2] + nums[i], robCurrentRoom[i - 1])
}
}
return robCurrentRoom[nums.count - 1]
}
/**
Title:198 House Robber
URL: https://leetcode.com/problems/house-robber/
Space: O(1)
Time: O(n)
*/
func coolRob(_ nums: [Int]) -> Int {
var robCurrent = 0
var robPre = 0
var robPrePre = 0
for num in nums {
robCurrent = max(robPre, robPrePre + num)
robPrePre = robPre
robPre = robCurrent
}
return robCurrent
}
}