-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0198.go
60 lines (51 loc) · 1.03 KB
/
0198.go
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
56
57
58
59
60
package main
func rob2(nums []int) int {
if len(nums) == 0 {
return 0
}
curMaxRob := 0
preMaxRob := 0
for _, number := range nums {
tmp := curMaxRob
curMaxRob = getTwoMaxNumber(preMaxRob+number, curMaxRob)
preMaxRob = tmp
}
return curMaxRob
}
func rob(nums []int) int {
if len(nums) == 0 {
return 0
}
robRes := make([]int, len(nums))
getMaxRob(len(nums)-1, nums, robRes)
return robRes[len(nums)-1]
}
func getMaxRob(index int, nums []int, robRes []int) bool {
if index == 0 {
robRes[0] = nums[0]
return true
}
robPre := getMaxRob(index-1, nums, robRes)
if robPre {
if index == 1 {
if nums[index] > robRes[index-1] {
robRes[index] = nums[1]
return true
} else {
robRes[index] = robRes[index-1]
return false
}
} else {
if nums[index]+robRes[index-2] > robRes[index-1] {
robRes[index] = nums[index] + robRes[index-2]
return true
} else {
robRes[index] = robRes[index-1]
return false
}
}
} else {
robRes[index] = robRes[index-1] + nums[index]
return true
}
}