In the Largest Divisible Subset problem, you are given a set of distinct positive integers. You need to find the largest subset such that every pair of elements in that subset satisfies either or . In simpler terms, every number in the subset must be a multiple or a divisor of every other number in that same subset.
This Array, Math, Sorting, Dynamic Programming interview pattern is frequently used by companies like Apple, Uber, and Oracle. It tests whether a candidate can recognize that sorting the input simplifies the "divisibility" condition. It also assesses ability to reconstruct a solution from DP state, rather than just returning a maximum length.
The solution uses Dynamic Programming on a sorted array.
dp[i] is the size of the largest divisible subset ending at index i.dp[i] = 1 + max(dp[j]) for all such that arr[i] % arr[j] == 0.parent array to track which j was used to get the max value for dp[i].Input: [1, 2, 4, 8, 7]
Sorted: [1, 2, 4, 7, 8]
dp[0] (1): [1], size 1dp[1] (2): 2 % 1 == 0, so [1, 2], size 2dp[2] (4): 4 % 2 == 0, so [1, 2, 4], size 3dp[3] (7): 7 % 1 == 0, so [1, 7], size 2dp[4] (8): 8 % 4 == 0, so [1, 2, 4, 8], size 4
Max size is 4. The subset is [1, 2, 4, 8].Practice "Longest Increasing Subsequence" (LIS) before this problem. Largest Divisible Subset is essentially LIS where the condition "greater than" is replaced by "is a multiple of." Understanding LIS will make this DP approach intuitive.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Allocate Mailboxes | Hard | Solve | |
| Maximum and Minimum Sums of at Most Size K Subsequences | Medium | Solve | |
| Count the Number of K-Free Subsets | Medium | Solve | |
| Super Ugly Number | Medium | Solve | |
| Minimum Moves to Equal Array Elements II | Medium | Solve |