forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestDivisibleSubset.java
More file actions
35 lines (29 loc) · 838 Bytes
/
LargestDivisibleSubset.java
File metadata and controls
35 lines (29 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int[] dp = new int[nums.length];
return constructLDS(nums, dp, getLDSSize(nums, dp));
}
private int getLDSSize(int[] nums, int[] dp) {
Arrays.sort(nums);
Arrays.fill(dp, 1);
int ldsSize = 1;
for (int i = 1; i < nums.length; i++)
for (int j = 0; j < i; j++)
if (nums[i] % nums[j] == 0) {
dp[i] = Math.max(dp[i], dp[j] + 1);
ldsSize = Math.max(ldsSize, dp[i]);
}
return ldsSize;
}
private List<Integer> constructLDS(int[] nums, int[] dp, int ldsSize) {
int prev = -1;
LinkedList<Integer> lds = new LinkedList<Integer>();
for (int i = dp.length - 1; i >= 0; i--)
if (dp[i] == ldsSize && (prev == -1 || prev % nums[i] == 0)) {
lds.addFirst(nums[i]);
ldsSize--;
prev = nums[i];
}
return lds;
}
}