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:
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 <= 10001 <= nums[i] <= 2 * 10^9All the integers in
numsare 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?