Program to find length of the largest subset where one element in every pair is divisible by other in Python

PythonServer Side ProgrammingProgramming

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
• ans := maximum of ans and dp[i]
• return ans

Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

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
Published on 12-Dec-2020 09:13:56
Advertisements