Talentd
FleetCode

368. Largest Divisible Subset

Medium50.1% acceptance6 companies

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, or
  • answer[j] % answer[i] == 0

If there are multiple solutions, return any of them.

Example 1:

Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.

Example 2:

Input: nums = [1,2,4,8]
Output: [1,2,4,8]

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 2 * 109
  • All the integers in nums are unique.
17:06
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,2,3]
Input
[1,2,4,8]
Your code is saved on this device.Solution