Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 298
Good morning! Here's your coding interview problem for today.

This problem was asked by Google.

A girl is walking along an apple orchard with a bag in each hand. She likes to pick apples from each tree as she goes along, but is meticulous about not putting different kinds of apples in the same bag.

Given an input describing the types of apples she will pass on her path, in order, determine the length of the longest portion of her path that consists of just two types of apple trees.

For example, given the input `[2, 1, 2, 3, 3, 1, 3, 5]`, the longest portion will involve types `1` and `3`, with a length of **four**.

Pull request description:
Day298
Resolves #609.

Patch:
diff --git a/README.md b/README.md
index bb4b972..d56bb3d 100644
--- a/README.md
+++ b/README.md
@@ -305,3 +305,4 @@ problems from
 * [Day 295](https://github.com/vaskoz/dailycodingproblem-go/issues/601)
 * [Day 296](https://github.com/vaskoz/dailycodingproblem-go/issues/605)
 * [Day 297](https://github.com/vaskoz/dailycodingproblem-go/issues/607)
+* [Day 298](https://github.com/vaskoz/dailycodingproblem-go/issues/609)
diff --git a/day298/problem.go b/day298/problem.go
new file mode 100644
index 0000000..a4c8f76
--- /dev/null
+++ b/day298/problem.go
@@ -0,0 +1,31 @@
+package day298
+
+// LongestAppleRun returns the length of the longest run of two types of apples.
+// Runs in O(N) time.
+func LongestAppleRun(apples []int) int {
+	lastIndex := make(map[int]int, 2)
+	var answer int
+	start := 0
+	for index, appleType := range apples {
+		lastIndex[appleType] = index
+		if len(lastIndex) > 2 {
+			if answer < index-start {
+				answer = index - start
+			}
+			var earliest int
+			min := int(^uint(0) >> 1)
+			for t, i := range lastIndex {
+				if i < min {
+					min = i
+					earliest = t
+				}
+			}
+			delete(lastIndex, earliest)
+			start = min + 1
+		}
+	}
+	if answer < len(apples)-start {
+		answer = len(apples) - start
+	}
+	return answer
+}


Test patch:
diff --git a/day298/problem_test.go b/day298/problem_test.go
new file mode 100644
index 0000000..39205c8
--- /dev/null
+++ b/day298/problem_test.go
@@ -0,0 +1,30 @@
+package day298
+
+import "testing"
+
+// nolint
+var testcases = []struct {
+	apples   []int
+	expected int
+}{
+	{[]int{2, 1, 2, 3, 3, 1, 3, 5}, 4},
+	{[]int{2, 1, 2, 2, 2, 1, 2, 1}, 8},
+	{[]int{4, 3, 2, 1}, 2},
+}
+
+func TestLongestAppleRun(t *testing.T) {
+	t.Parallel()
+	for _, tc := range testcases {
+		if result := LongestAppleRun(tc.apples); result != tc.expected {
+			t.Errorf("Expected %v, got %v", tc.expected, result)
+		}
+	}
+}
+
+func BenchmarkLongestAppleRun(b *testing.B) {
+	for i := 0; i < b.N; i++ {
+		for _, tc := range testcases {
+			LongestAppleRun(tc.apples)
+		}
+	}
+}