Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The largest chain of divisors

Medium · Target 20 minutes · Dynamic programming · Type asked atGoogleAmazon

Given distinct positive integers nums, return the size of the largest subset in which, for every pair (a, b), either a divides b or b divides a.

Examples

InputOutputWhy
nums = [1,2,3]2{1, 2} or {1, 3}.
nums = [1,2,4,3,8,6,24]5{1, 2, 4, 8, 24}.
nums = [2,3,5,7]1Primes: no pair works.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 2 · 10⁹, all distinct

Hints

Hint 1

Sort the numbers. In a valid subset, each element then divides the next.

Hint 2

Divisibility is transitive: if a | b and b | c then a | c, so checking neighbours is enough.

Hint 3

end[i] = 1 + max end[j] over j < i with nums[i] % nums[j] == 0.

Where people lose marks

  • Not sorting first, so a divisor can appear after its multiple.
  • Checking every pair in the chain instead of relying on transitivity (correct, but slower).
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.