Leetcode 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:
If there are multiple solutions, return any subset.
n
?
Examples:
2
and 4
, and since 4 % 2 == 0
, any number which is divisible by 4
will also be divisible by 2
.dp
where dp[i]
represents the length of the largest divisible subset ending with nums[i]
.prev
to keep track of the previous element index in the subset.prev
array.prev
array.import java.util.*;
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
Arrays.sort(nums);
int n = nums.length;
int[] dp = new int[n];
int[] prev = new int[n];
// Initialize dp array: each element is a subset of length 1
Arrays.fill(dp, 1);
Arrays.fill(prev, -1);
int maxIndex = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
prev[i] = j;
}
}
if (dp[i] > dp[maxIndex]) {
maxIndex = i;
}
}
List<Integer> result = new ArrayList<>();
for (int i = maxIndex; i >= 0; i = prev[i]) {
result.add(nums[i]);
if (prev[i] == i) {
break;
}
}
Collections.reverse(result);
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums1 = {1, 2, 3};
System.out.println(sol.largestDivisibleSubset(nums1)); // Output: [1, 2] or [1, 3]
int[] nums2 = {1, 2, 4, 8};
System.out.println(sol.largestDivisibleSubset(nums2)); // Output: [1, 2, 4, 8]
}
}
O(n^2)
where n
is the length of the input array. This is due to the double nested loop to fill up the DP array.O(n)
for the DP and previous index arrays.The implementation is efficient for the given constraints and follows a dynamic programming approach to solve the problem optimally.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?