- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

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

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

- Related Questions & Answers
- C++ Program to find the Largest Divisible Pairs Subset
- C++ Program to find the Largest Divisible Subset in Array
- C++ code to find pair of numbers where one is multiple of other
- C++ Largest Subset with Sum of Every Pair as Prime
- 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
- Program to find maximum size of any sequence of given array where every pair is nice in Python
- Program to find out the index in an array where the largest element is situated in Python
- Python program to find the size of largest subset of anagram words
- 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
- Program to find smallest pair sum where distance is not consecutive in Python

Advertisements