Largest Divisible Subset
LeetCode Problem #368 (Medium)
Problem Statement
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj)
of elements in this subset satisfies:
Si % Sj = 0
or Sj % Si = 0
Testcases
Problem Explanation
From a given set of unique positive integers, we must compare pairs of elements to see if either of the integers are divisible by the other. If the condition is satisfied, we create a subset with these integers. We must return the longest possible subset which can satisfy this condition.
Example:
Consider the input array as: [1, 2, 3]
Prerequisite Knowledge
Subset
A subset is a set of zero or more elements which is contained within a larger set of elements. The definition of a subset does not stipulate that the subset must maintain the relative order of the original set. That is, the order of the elements in the subset does not have to be sequentially equivalent to the set from which it has been derived.
Example
Let us consider the string "coding".
The sequence of elements in this string is as follows:
A subset of the characters from the original set must contain only characters which belong to the original set but does not have to maintain the relative order in which they are present in that set.
Correct Subset: [i, o, n]
Incorrect Subset: [c, s, n]
For a sequence of size n, we can have a total of (2^n) subsets.
Refer to the Prerequisite Knowledge section in Is Subsequence to understand the difference between a subsequence and a subset:
Dynamic Programming
Refer to the Prerequisite Knowledge section in Coin Change 2:
Algorithm
Bottom-Up DP Approach
Calculate the size of the input array and check if it is empty.
Sort the array in ascending order such that we only have to compare the value of nums[j] % nums[i] and not nums[i] % nums[j].
Create a vector to build the DP table with the length of the longest subset.
Create a vector to store and track the indices of previous elements in a subset such that when we build a bigger subset, we can include those elements.
Iterate through the input array such that j < i < n and add nums[i] to the subset if and only if:
a. nums[i] % nums[j] == 0
b. If nums[i] is added to the subset which ends with nums[j], the length of the new subset is greater than the current subset.
Keep track of the previous indices in each iteration and the maximum index value.
Create a resultant vector to build the longest subset using the maximum index value and previous indices.
Code
Last updated
Was this helpful?