Largest Divisible Subset

Dynamic Programming LIS Easy

Given an array nums of positive integers, the task is to find the largest subset such that every pair (a, b) of elements in the subset satisfies a % b == 0 or b % a == 0. Return the subset in sorted order. If there are multiple solutions, return any one of them.

Examples:

Input: nums = [3, 5, 10, 20]

Output: [5, 10, 20]

Explanation: The subset [5, 10, 20] satisfies the divisibility condition: 10 % 5 == 0 and 20 % 10 == 0.

Input: nums = [16, 8, 2, 4, 32]

Output: [2, 4, 8, 16, 32]

Explanation: The entire array forms a divisible subset since 32 % 16 == 0, 16 % 8 == 0, and so on.

Input: nums = [7, 14, 28, 3]

Constraints

  • 1 <= nums.length <= 103
  • 1 <= nums[i] <= 106

Hints

  • A Dynamic Programming (DP) approach efficiently solves this problem by Sorting nums in ascending order ensures that if nums[j] divides nums[i], then nums[i] is always greater than nums[j].
  • "Using DP (dp[i]) to track the size of the largest divisible subset ending at index i. Maintaining a parent[] array to reconstruct the subset efficiently."