# Question

Formatted question description: https://leetcode.ca/all/368.html

 368	Largest Divisible Subset

Given a set of distinct positive integers,
find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0
or Sj % Si = 0.

If there are multiple solutions, return any subset is fine.

Example 1:

Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)

Example 2:

Input: [1,2,4,8]
Output: [1,2,4,8]

@tag-dp


# Algorithm

The remainder of the smaller number to the larger number must not be 0, then the question becomes whether the larger number can divide the smaller number evenly.

So if the array is unordered, it will be more troublesome to process, so we can sort the array first, so that we only need to see whether the following numbers can divide the previous numbers every time.

Define a dynamic array dp, where dp[i] represents the length of the largest divisible subset of the number nums[i] position.

A one-dimensional array parent is also needed to store the position of the last divisible number. The two integer variables mx and mx_idx respectively represent the length of the largest subset and the position of the starting number.

We can traverse the array from back to front, and then traverse to the end for a certain number. In this process,

• If nums[j] can divide nums[i] evenly, and dp[i] <dp[j] + 1, update dp[i] and parent[i],
• If dp[i] is greater than mx, update mx and mx_idx, After the end of the loop, we fill in the res number and find each number according to the parent array.

Java