
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- C++ Program to find the Largest Divisible Subset in Array
- C++ Program to find the Largest Divisible Pairs Subset
- 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++
- Program to find maximum size of any sequence of given array where every pair is nice in Python
- C++ code to find pair of numbers where one is multiple of other
- 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
- Check if one list is subset of other in Python
- Check if one tuple is subset of other in Python
- Program to Find Out the Largest K-Divisible Subsequence Sum in Python
- Find the element that appears once in an array where every other element appears twice in C++
- Python Program to find the largest element in an array
- Python Program to find the largest element in a tuple

Advertisements