Largest Divisible Subset

Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) satisfies answer[i] % answer[j] == 0 or answer[j] % answer[i] == 0. If there are several largest subsets, any of them is accepted on LeetCode. Here every hidden test has exactly one largest subset, and the reference returns it in ascending order (any order is accepted).

30:00

Largest Divisible Subset
medium
Free written solution
Topics
Companies

Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) satisfies answer[i] % answer[j] == 0 or answer[j] % answer[i] == 0. If there are several largest subsets, any of them is accepted on LeetCode. Here every hidden test has exactly one largest subset, and the reference returns it in ascending order (any order is accepted).

Example 1:
Input: {"nums":[1,2,3]}
Output: [1,2]
Constraints:
  • 1≤nums.length≤10001 \leq \text{nums.length} \leq 1000

  • 1≤nums[i]≤2×1091 \leq \text{nums}[i] \leq 2 \times 10^9

  • All the integers in nums are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3]}

Sort the 3 numbers: [1, 2, 3]. In sorted order, a divisible subset is a chain where each number divides the next one.

sorted nums · dp = chain size ending here · ← prev in chain

1

·

—

2

·

—

3

·

—

best chain so far (size 0)

none yet

Variables
VariableValue
n3
best0
DepthFunction Call
Stack empty
0/10