8000 :sparkles: Added solution to 198 · ninefive/awesome-golang-leetcode@b858962 · GitHub
[go: up one dir, main page]

Skip to content

Commit b858962

Browse files
author
Sathish Babu
committed
✨ Added solution to 198
1 parent 61106b8 commit b858962

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/0198.House-Robber/Solution.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,22 @@ func rob3(nums []int) int {
3636
return max(robEven, robOdd)
3737
}
3838

39+
func rob4(nums []int) int {
40+
n := len(nums)
41+
if n == 0 {
42+
return 0
43+
}
44+
if n == 1 {
45+
return nums[0]
46+
}
47+
dp := make([]int, n)
48+
dp[0], dp[1] = nums[0], max(nums[0], nums[1])
49+
for i := 2; i < n; i++ {
50+
dp[i] = max(nums[i]+dp[i-2], dp[i-1])
51+
}
52+
return dp[n-1]
53+
}
54+
3955
func max(x, y int) int {
4056
if x > y {
4157
return x

src/0198.House-Robber/Solution_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package Solution
22

33
import (
44
"reflect"
5+
"strconv"
56
"testing"
67
)
78

@@ -75,6 +76,32 @@ func TestSolution3(t *testing.T) {
7576
}
7677
}
7778

79+
func TestSolution4(t *testing.T) {
80+
// 测试用例
81+
cases := []struct {
82+
name string
83+
inputs []int
84+
expect int
85+
}{
86+
{"TestCacse", []int{}, 0},
87+
{"TestCacse", []int{3}, 3},
88+
{"TestCacse", []int{1, 2, 3, 1}, 4},
89+
{"TestCacse", []int{2, 7, 9, 3, 1}, 12},
90+
{"TestCacse", []int{5, 2, 6, 7, 3, 1}, 14},
91+
}
92+
93+
// 开始测试
94+
for i, c := range cases {
95+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
96+
got := rob4(c.inputs)
97+
if !reflect.DeepEqual(got, c.expect) {
98+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
99+
c.expect, got, c.inputs)
100+
}
101+
})
102+
}
103+
}
104+
78105
// 压力测试
79106
func BenchmarkSolution(b *testing.B) {
80107

0 commit comments

Comments
 (0)
0