Largest Divisible Subset

Implement largestDivisibleSubset

Given an array of distinct integers, find the largest subset where every pair of numbers is compatible in a division sense — for any two numbers in the subset, the larger one is evenly divisible by the smaller one. Sorting the numbers first turns this into a subsequence problem: once ascending, any valid subset lines up in that same increasing order, because a bigger multiple can only be evenly divisible by a smaller factor that came before it. That makes it possible to ask, for every number, "what's the best divisible chain that ends here?" — check every earlier, smaller number, and whenever it evenly divides the current one, the chain ending there could be extended. Solving that sub-problem once per number, in ascending order, and remembering which earlier number produced each best chain, is enough to reconstruct the whole thing afterward.

Example 1:

Input: nums = [2,4,5]

Output: [2,4]

Example 2:

Input: nums = [3,6,12,24]

Output: [3,6,12,24]

Example 3:

Input: nums = [3,4,16,8]

Output: [4,8,16]

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10
  • 1 ≤ nums[i] ≤ 1000
  • All the integers in nums are distinct
  • If more than one largest divisible subset exists, return the one built by sorting nums ascending first and always preferring the smallest-index predecessor whenever two predecessors would extend a chain to the same length

nums =

[2, 4, 5]