Skip to content

Commit

Permalink
day 191: minimum intervals to remove to avoid overlaps
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Mar 1, 2019
1 parent 5f7df16 commit b2f49be
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
26 changes: 26 additions & 0 deletions day191/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package day191

import "sort"

// Interval has a start and end.
type Interval struct {
Start, End int
}

// MinRemoveNoOverlap returns the minimum number of intervals
// to remove to remove all overlaps.
// Runs in O(N log N) time.
func MinRemoveNoOverlap(intervals []Interval) int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i].End < intervals[j].End
})
count := 0
current := -int(^uint(0)>>1) - 1
for _, interval := range intervals {
if interval.Start >= current {
count++
current = interval.End
}
}
return len(intervals) - count
}
27 changes: 27 additions & 0 deletions day191/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package day191

import "testing"

var testcases = []struct {
intervals []Interval
removes int
}{
{[]Interval{{7, 9}, {2, 4}, {5, 8}}, 1},
}

func TestMinRemoveNoOverlap(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := MinRemoveNoOverlap(tc.intervals); result != tc.removes {
t.Errorf("Expected %v, got %v", tc.removes, result)
}
}
}

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

0 comments on commit b2f49be

Please sign in to comment.