Skip to content

Commit

Permalink
Merge 04bb33e into 9caad7c
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Mar 10, 2019
2 parents 9caad7c + 04bb33e commit 98be3e0
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,5 +207,6 @@ problems from
* [Day 195](https://github.com/vaskoz/dailycodingproblem-go/issues/401)
* [Day 196](https://github.com/vaskoz/dailycodingproblem-go/issues/404)
* [Day 197](https://github.com/vaskoz/dailycodingproblem-go/issues/405)
* [Day 198](https://github.com/vaskoz/dailycodingproblem-go/issues/408)
* [Day 199](https://github.com/vaskoz/dailycodingproblem-go/issues/409)
* [Day 200](https://github.com/vaskoz/dailycodingproblem-go/issues/411)
45 changes: 45 additions & 0 deletions day198/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package day198

import (
"sort"
)

// LargestSubsetPairs finds the largest subset
// such that every pair of elements in the subset (i, j)
// satisfies either i % j = 0 or j % i = 0.
// Runs in O(N^2) time
func LargestSubsetPairs(nums []int) []int {
sort.Slice(nums, func(i, j int) bool {
return nums[i] < nums[j]
})
dp := make([]int, len(nums))
dp[len(dp)-1] = 1
var largestI, largestVal int
for i := len(dp) - 2; i >= 0; i-- {
m := 0
for j := i + 1; j < len(dp); j++ {
if nums[j]%nums[i] == 0 {
m = max(m, dp[j])
}
}
dp[i] = 1 + m
if dp[i] > largestVal {
largestI = i
largestVal = dp[i]
}
}
result := make([]int, 0, largestVal)
for i := largestI; i < len(nums); i++ {
if nums[i]%nums[largestI] == 0 {
result = append(result, nums[i])
}
}
return result
}

func max(a, b int) int {
if a > b {
return a
}
return b
}
32 changes: 32 additions & 0 deletions day198/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package day198

import (
"reflect"
"testing"
)

var testcases = []struct {
nums, subset []int
}{
{[]int{3, 5, 10, 20, 21}, []int{5, 10, 20}},
{[]int{1, 3, 6, 24}, []int{1, 3, 6, 24}},
}

func TestLargestSubsetPairs(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
input := append([]int{}, tc.nums...)
if result := LargestSubsetPairs(input); !reflect.DeepEqual(result, tc.subset) {
t.Errorf("Expected %v, got %v", tc.subset, result)
}
}
}

func BenchmarkLargestSubsetPairs(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
input := append([]int{}, tc.nums...)
LargestSubsetPairs(input)
}
}
}

0 comments on commit 98be3e0

Please sign in to comment.