-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSolution.java
46 lines (34 loc) · 1.14 KB
/
Solution.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
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
//if array is empty
int len = nums.length;
if(nums == null || len == 0)
return new ArrayList<Integer>();
Arrays.sort(nums);
int[] dp = new int[len];
Arrays.fill(dp, 1);
for(int i = 1; i < len; i++){
for(int j = i-1; j >= 0; j--){
if(nums[i] % nums[j] == 0)
dp[i] = Math.max(dp[i], dp[j]+1);
}
}
//get maxIndex
int maxIndex = 0;
for(int i = 1; i < len; i++){
if(dp[i] > dp[maxIndex])
maxIndex = i;
}
ArrayList<Integer> res = new ArrayList<Integer>();
int currNum = nums[maxIndex];
int currCount = dp[maxIndex];
for(int i = maxIndex; i >=0; i--){
if(currNum % nums[i] == 0 && dp[i] == currCount){
res.add(nums[i]);
currNum = nums[i];
currCount--;
}
}
return res;
}
}