Question
Formatted question description: https://leetcode.ca/all/368.html
368 Largest Divisible Subset
Given a set of distinct positive integers,
find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0
or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:
Input: [1,2,4,8]
Output: [1,2,4,8]
@tag-dp
Algorithm
The remainder of the smaller number to the larger number must not be 0, then the question becomes whether the larger number can divide the smaller number evenly.
So if the array is unordered, it will be more troublesome to process, so we can sort the array first, so that we only need to see whether the following numbers can divide the previous numbers every time.
Define a dynamic array dp, where dp[i]
represents the length of the largest divisible subset of the number nums[i] position
.
A one-dimensional array parent
is also needed to store the position of the last divisible number. The two integer variables mx
and mx_idx
respectively represent the length of the largest subset and the position of the starting number.
We can traverse the array from back to front, and then traverse to the end for a certain number. In this process,
- If nums[j] can divide nums[i] evenly, and
dp[i] <dp[j] + 1
, update dp[i] and parent[i], - If dp[i] is greater than mx, update mx and mx_idx, After the end of the loop, we fill in the res number and find each number according to the parent array.
Code
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Largest_Divisible_Subset {
public static void main(String[] args) {
Largest_Divisible_Subset out = new Largest_Divisible_Subset();
Solution s = out.new Solution();
System.out.println(s.largestDivisibleSubset(new int[]{1,2,3,4,7,8}));
}
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
List<Integer> res = new ArrayList<>();
int[] dp = new int[nums.length];
int[] parent = new int[nums.length];
int maxLength = 0, maxIndex = 0;
// i is from back to front, so that when out of loop, maxIndex is at the smallest index to trace back
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = i; j < nums.length; j++) {
if (nums[j] % nums[i] == 0 && dp[i] < dp[j] + 1) {
// dp[i] <= dp[j] + 1, also working but repeated write
dp[i] = dp[j] + 1;
parent[i] = j;
if (maxLength < dp[i]) {
maxLength = dp[i];
maxIndex = i;
}
}
}
}
for (int i = 0; i < maxLength; ++i) {
// back-tracking
res.add(nums[maxIndex]);
maxIndex = parent[maxIndex];
}
return res;
}
}
}