-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargestDivisibleSubset.java
51 lines (39 loc) · 1.35 KB
/
largestDivisibleSubset.java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
/*
Copied soln i haven't study dp
The basic idea is like:
1. Sort
2. Find the length of longest subset
3. Record the largest element of it.
4. Do a loop from the largest element to nums[0], add every element belongs to the longest subset.
*/
List<Integer> res = new ArrayList<Integer>();
if (nums == null || nums.length == 0)
return res;
Arrays.sort(nums);
int[] dp = new int[nums.length];
for(int i = 0; i < dp.length; i++){
dp[i] +=1;
}
for(int i = 0; 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);
}
int maxIndex = 0;
for (int i = 1; i < nums.length; i++)
maxIndex = dp[i] > dp[maxIndex]? i: maxIndex;
int temp = nums[maxIndex];
int curDp = dp[maxIndex];
for(int i = maxIndex; i>=0; i--){
if(temp % nums[i] == 0 && dp[maxIndex] - dp[i] <=1){
res.add(nums[i]);
temp = nums[i];
maxIndex = i;
}
}
Collections.sort(res);
return res;
}
}