- Related Questions & Answers
- Divide every element of one array by other array elements in C++ Program
- Largest Divisible Subset in C++
- Check if one list is subset of other in Python
- Check if one tuple is subset of other in Python
- Python program to find the size of largest subset of anagram words
- Program to find out the index in an array where the largest element is situated in Python
- Python program to find the size of the largest subset of anagram words
- Find the element that appears once in an array where every other element appears twice in C++
- Program to Find Out the Largest K-Divisible Subsequence Sum in Python
- Python Program to find the largest element in an array
- Program to Find the longest subsequence where the absolute difference between every adjacent element is at most k in Python.
- Program to find largest distance pair from two list of numbers in Python
- Program to find the sum of the absolute differences of every pair in a sorted list in Python
- Python Program to find largest element in an array
- MySQL query to find all rows where ID is divisible by 4?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

[3, 6, 12, 24, 26, 39]

4

Advertisements