Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1e01d6e

Browse files
committed
Add: House Robber
1 parent 9584d0c commit 1e01d6e

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,12 @@
11
package house_robber
2+
3+
func rob(nums []int) int {
4+
pre1, pre2, ans := 0, 0, 0
5+
for _, v := range nums {
6+
if ans = pre1 + v; pre2 > ans {
7+
ans = pre2
8+
}
9+
pre1, pre2 = pre2, ans
10+
}
11+
return ans
12+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,27 @@
11
package house_robber
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestRob(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{1, 2, 3, 1},
14+
expected: 4,
15+
},
16+
{
17+
input: []int{2, 7, 9, 3, 1},
18+
expected: 12,
19+
},
20+
}
21+
for _, tc := range tests {
22+
output := rob(tc.input)
23+
if output != tc.expected {
24+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
25+
}
26+
}
27+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /