Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Feb 9, 2024
1 parent 66704cf commit 3ba7e8e
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions leetcode/368.LargestDivisibleSubset/largestDivisibleSubset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// https://leetcode.com/problems/largest-divisible-subset

package main

import (
"fmt"
"sort"
)

func largestDivisibleSubset(nums []int) []int {
res := []int{}
sort.Ints(nums)

n := len(nums)
f := make([]int, n)
k := 0

for i := 0; i < n; i++ {
f[i] = 1
for j := 0; j < i; j++ {
if nums[i]%nums[j] == 0 {
f[i] = max(f[i], f[j]+1)
}
}
if f[k] < f[i] {
k = i
}
}

m := f[k]
for i := k; m > 0; i-- {
if nums[k]%nums[i] == 0 && f[i] == m {
res = append(res, nums[i])
k = i
m--
}
}

return res
}

func max(a, b int) int {
if a > b {
return a
}
return b
}

func main() {
nums := []int{1, 2, 3}

fmt.Println(largestDivisibleSubset(nums))
}

0 comments on commit 3ba7e8e

Please sign in to comment.