Skip to content

Commit

Permalink
day 464: cleaned up day 198
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Feb 28, 2020
1 parent de0a74a commit 06cce03
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
52 changes: 52 additions & 0 deletions day464/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package day464

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
largestI, largestVal := 0, 0

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])
}
}

if dp[i] = 1 + m; 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
}
34 changes: 34 additions & 0 deletions day464/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package day464

import (
"reflect"
"testing"
)

// nolint
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 06cce03

Please sign in to comment.