Skip to content

Commit bb1351b

Browse files
authored
Create largestDivisibleSubset.java
1 parent 0e143a3 commit bb1351b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

largestDivisibleSubset.java

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
public List<Integer> largestDivisibleSubset(int[] nums) {
3+
4+
/*
5+
6+
Copied soln i haven't study dp
7+
8+
The basic idea is like:
9+
10+
1. Sort
11+
2. Find the length of longest subset
12+
3. Record the largest element of it.
13+
4. Do a loop from the largest element to nums[0], add every element belongs to the longest subset.
14+
15+
16+
17+
*/
18+
19+
List<Integer> res = new ArrayList<Integer>();
20+
if (nums == null || nums.length == 0)
21+
return res;
22+
Arrays.sort(nums);
23+
int[] dp = new int[nums.length];
24+
for(int i = 0; i < dp.length; i++){
25+
dp[i] +=1;
26+
}
27+
28+
for(int i = 0; i < nums.length; i++)
29+
for(int j = 0; j <i ; j++){
30+
if(nums[i] % nums[j] == 0)
31+
dp[i] = Math.max(dp[i], dp[j] +1);
32+
}
33+
34+
int maxIndex = 0;
35+
for (int i = 1; i < nums.length; i++)
36+
maxIndex = dp[i] > dp[maxIndex]? i: maxIndex;
37+
38+
int temp = nums[maxIndex];
39+
int curDp = dp[maxIndex];
40+
for(int i = maxIndex; i>=0; i--){
41+
if(temp % nums[i] == 0 && dp[maxIndex] - dp[i] <=1){
42+
res.add(nums[i]);
43+
temp = nums[i];
44+
maxIndex = i;
45+
}
46+
}
47+
Collections.sort(res);
48+
return res;
49+
50+
}
51+
}

0 commit comments

Comments
 (0)