368. Largest Divisible Subset
LeetCode 368. Largest Divisible Subset
Description
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.
Example 1:
Example 2:
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 2 * 10^9
All the integers in
nums
are unique.
Tags
Math, Dynamic Programming
Solution
We first sort the input array so that we only need to evaluate nums[large]%nums[small] == 0
afterwards. We also initialize 2 arrays of length len(nums)
, to keep track of the longest subsequence at index i
and its previous state. Iterating over nums, we first initialize the longest length and previous state with 1 and i
respectively, then update both when nums[i]%nums[j] == 0
and find a longer sequence longLen[j]+1
. After loop, we obtain the max length and its index, and collect all elements starting from such index along with states.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?