This repository contains a Python solution to LeetCode Problem 368 - Largest Divisible Subset.
Given a set of distinct positive integers nums
, return the largest subset answer
such that every pair (answer[i], answer[j])
of elements in this subset satisfies:
answer[i] % answer[j] == 0
, oranswer[j] % answer[i] == 0
If there are multiple solutions, return any of them.
1 <= nums.length <= 1000
1 <= nums[i] <= 2 * 10^9
- All the integers in
nums
are unique
This problem is solved using Dynamic Programming:
- Sort the array to ensure proper divisibility order.
- Use a
dp[]
array to keep track of the size of the largest divisible subset ending at each index. - Use a
prev[]
array to remember the previous index of the number in the subset chain. - Reconstruct the subset by backtracking from the largest value found.
Time Complexity: O(n^2)
Space Complexity: O(n)
leetcode-368-largest-divisible-subset
- #DynamicProgramming
- #Subsets
- #Greedy
- #Math
- #Medium
👉 LeetCode Problem 368 - Largest Divisible Subset