Suppose we have a list of unique numbers called nums, so we have to find the largest subset such that every pair of elements in the subset like (i, j) satisfies either i % j = 0 or j % i = 0. So we have to find the size of this subset.
So, if the input is like nums = [3, 6, 12, 24, 26, 39], then the output will be 4, as the largest valid subset is [3, 6, 12, 24].
To solve this, we will follow these steps −
- dp := a list of size nums and fill with 1
- sort the list nums
- n := size of nums
- if n <= 1, then
- return n
- ans := 0
- for i in range 1 to n, do
- for j in range 0 to i, do
- if nums[i] is divisible by nums[j], then
- dp[i] := maximum of dp[i] and dp[j] + 1
- if nums[i] is divisible by nums[j], then
- ans := maximum of ans and dp[i]
- for j in range 0 to i, do
- return ans
Example (Python)
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): dp = [1] * len(nums) nums.sort() n = len(nums) if n <= 1: return n ans = 0 for i in range(1, n): for j in range(0, i): if nums[i] % nums[j] == 0: dp[i] = max(dp[i], dp[j] + 1) ans = max(ans, dp[i]) return ans ob = Solution() nums = [3, 6, 12, 24, 26, 39] print(ob.solve(nums))
Input
[3, 6, 12, 24, 26, 39]
Output
4