712816. Largest Divisible Subset
Medium
Largest Divisible Subset
Summary
Given an array A of integers, find the largest subset of A such that every pair of elements in the subset can be divided by some integer. In other words, for any two numbers a and b in the subset, there exists a number k such that a % k == 0 and b % k == 0. The goal is to find the largest such subset.
Detailed Explanation
The problem can be solved using dynamic programming. We initialize an array dp of size n, where n is the length of the input array A. Each element dp[i] represents the largest divisible subset ending at index i.
Here's a step-by-step breakdown of the solution:
- Initialize
dp[0] = 1, since the largest divisible subset ending at the first element is just that single element. - Iterate through the array from the second element to the last:
- For each element
A[i], find the maximum integerksuch thatA[j] % k == 0for somej < i. This can be done using a simple linear search. - Update
dp[i] = max(dp[i], dp[j] + 1), wherejis the index of the previous element that is divisible byk.
- For each element
- The maximum value in the
dparray represents the size of the largest divisible subset.
Time complexity: O(n log n), since we perform a linear search for each element to find the maximum integer k. Space complexity: O(n), for the dynamic programming array.
Optimized Solutions
Java
public int largestDivisibleSubset(int[] A) {
int n = A.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int maxLen = 0;
int idx = -1;
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
if (A[i] % A[j] == 0 && dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
}
}
if (dp[i] > maxLen) {
maxLen = dp[i];
idx = i;
}
}
return maxLen;
}