Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day75 #160

Merged
merged 2 commits into from
Nov 5, 2018
Merged

Day75 #160

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,4 @@ problems from
* [Day 72](https://github.com/vaskoz/dailycodingproblem-go/issues/153)
* [Day 73](https://github.com/vaskoz/dailycodingproblem-go/issues/155)
* [Day 74](https://github.com/vaskoz/dailycodingproblem-go/issues/157)
* [Day 75](https://github.com/vaskoz/dailycodingproblem-go/issues/159)
39 changes: 39 additions & 0 deletions day75/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package day75

// LongestIncreasingSubsequence returns the longest increasing subsequence.
// Runs in O(N log N) time.
func LongestIncreasingSubsequence(X []int) []int {
p := make([]int, len(X))
m := make([]int, len(X)+1)
l := 0
for i := range X {
lo := 1
hi := l
for lo <= hi {
var mid int
if (lo+hi)%2 == 0 {
mid = (lo + hi) / 2
} else {
mid = ((lo + hi) / 2) + 1
}
if X[m[mid]] < X[i] {
lo = mid + 1
} else {
hi = mid - 1
}
}
newL := lo
p[i] = m[newL-1]
m[newL] = i
if newL > l {
l = newL
}
}
s := make([]int, l)
k := m[l]
for i := range s {
s[len(s)-1-i] = X[k]
k = p[k]
}
return s
}
30 changes: 30 additions & 0 deletions day75/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package day75

import (
"reflect"
"testing"
)

var testcases = []struct {
input, expected []int
}{
{[]int{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15},
[]int{0, 2, 6, 9, 11, 15}},
}

func TestLongestIncreasingSubsequence(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := LongestIncreasingSubsequence(tc.input); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkLongestIncreasingSubsequence(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
LongestIncreasingSubsequence(tc.input)
}
}
}