Skip to content

Commit

Permalink
Merge 623bdcb into 83ebc79
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Aug 21, 2019
2 parents 83ebc79 + 623bdcb commit dee5454
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,4 @@ problems from
* [Day 361](https://github.com/vaskoz/dailycodingproblem-go/issues/712)
* [Day 362](https://github.com/vaskoz/dailycodingproblem-go/issues/714)
* [Day 363](https://github.com/vaskoz/dailycodingproblem-go/issues/716)
* [Day 364](https://github.com/vaskoz/dailycodingproblem-go/issues/718)
38 changes: 38 additions & 0 deletions day364/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package day364

// LongestIncreasingSubsequence returns the longest increasing
// subsequence.
// Runs in O(N log N) time with O(N) extra space.
func LongestIncreasingSubsequence(seq []int) []int {
p := make([]int, len(seq))
m := make([]int, len(seq)+1)
var l int
for i := range seq {
lo := 1
hi := l
for lo <= hi {
mid := (lo + hi) / 2
if (lo+hi)%2 != 0 {
mid++
}
if seq[m[mid]] <= seq[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 := len(s) - 1; i >= 0; i-- {
s[i] = seq[k]
k = p[k]
}
return s
}
31 changes: 31 additions & 0 deletions day364/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package day364

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
seq []int
lis []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.seq); !reflect.DeepEqual(result, tc.lis) {
t.Errorf("Expected %v, got %v", tc.lis, result)
}
}
}

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

0 comments on commit dee5454

Please sign in to comment.