Skip to content

Commit

Permalink
Merge 68262ab into 6e72252
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 22, 2019
2 parents 6e72252 + 68262ab commit 5e236f0
Show file tree
Hide file tree
Showing 3 changed files with 120 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,4 +389,5 @@ problems from
* [Day 394](https://github.com/vaskoz/dailycodingproblem-go/issues/791)
* [Day 395](https://github.com/vaskoz/dailycodingproblem-go/issues/793)
* [Day 396](https://github.com/vaskoz/dailycodingproblem-go/issues/795)
* [Day 397](https://github.com/vaskoz/dailycodingproblem-go/issues/797)

54 changes: 54 additions & 0 deletions day397/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package day397

import "sort"

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

// LargestSubsetCompatibleJobs returns the largest
// subset of compatible jobs. Compatible jobs are non-overlapping.
func LargestSubsetCompatibleJobs(jobs []Job) []Job {
copied := append([]Job{}, jobs...)
sort.Slice(copied, func(i, j int) bool {
if copied[i].End < copied[j].End {
return true
} else if copied[i].End == copied[j].End {
return copied[i].Start < copied[j].Start
}

return false
})

possible := make([][]Job, 0)

for _, job := range copied {
added := false

for i, p := range possible {
left := p[len(p)-1]

if job.Start >= left.End {
possible[i] = append(p, job)
}
}

if !added {
possible = append(possible, []Job{job})
}
}

largestSize := 0

var largest []Job

for _, p := range possible {
if len(p) > largestSize {
largestSize = len(p)
largest = p
}
}

return largest
}
65 changes: 65 additions & 0 deletions day397/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package day397

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
jobs, expected []Job
}{
{
[]Job{
{0, 6},
{1, 4},
{3, 5},
{3, 8},
{4, 7},
{5, 9},
{6, 10},
{8, 11},
},
[]Job{
{1, 4},
{4, 7},
{8, 11},
},
},
{
[]Job{
{0, 100},
{1, 3},
{3, 5},
{0, 10},
{6, 8},
{9, 10},
{6, 10},
{8, 11},
},
[]Job{
{1, 3},
{3, 5},
{6, 8},
{9, 10},
},
},
}

func TestLargestSubsetCompatibleJobs(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if res := LargestSubsetCompatibleJobs(tc.jobs); !reflect.DeepEqual(res, tc.expected) {
t.Errorf("Expected %v, got %v", tc.expected, res)
}
}
}

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

0 comments on commit 5e236f0

Please sign in to comment.