-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestDivisibleSubset.java
More file actions
75 lines (67 loc) · 2.49 KB
/
LargestDivisibleSubset.java
File metadata and controls
75 lines (67 loc) · 2.49 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package leetcode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* LargestDivisibleSubset
* https://leetcode-cn.com/problems/largest-divisible-subset/
* 368. 最大整除子集
* https://leetcode-cn.com/problems/largest-divisible-subset/solution/bao-li-sou-suo-jie-ti-by-oshdyr-zi3j/
*
* @since 2021-04-23
*/
public class LargestDivisibleSubset {
public static void main(String[] args) {
LargestDivisibleSubset sol = new LargestDivisibleSubset();
// List<Integer> res = sol.largestDivisibleSubset(new int[]{1, 2, 4, 8});
// List<Integer> res = sol.largestDivisibleSubset(new int[]{1, 2, 3});
// List<Integer> res = sol.largestDivisibleSubset(new int[]{1, 2, 3, 6});
// List<Integer> res = sol.largestDivisibleSubset(new int[]{1, 2, 3, 6, 9, 12});
List<Integer> res = sol.largestDivisibleSubset(new int[]{1, 2, 3, 6, 9, 12, 108});
System.out.println(res.size());
for (Integer re : res) {
System.out.print(re + ", ");
}
System.out.println();
}
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> allNums = new ArrayList<>(nums.length);
for (int num : nums) {
allNums.add(num);
}
Collections.sort(allNums);
int totalMaxLength = 1;
int totalMaxIndex = 0;
int[] dividerIndex = new int[nums.length];
int[] maxLength = new int[nums.length];
dividerIndex[0] = -1;
maxLength[0] = 1;
for (int i = 1; i < allNums.size(); i++) {
dividerIndex[i] = -1;
maxLength[i] = 1;
for (int lastI = i - 1; lastI >= 0; lastI--) {
if (maxLength[lastI] < maxLength[i]) {
continue;
}
if (allNums.get(i) % allNums.get(lastI) == 0) {
maxLength[i] = maxLength[lastI] + 1;
dividerIndex[i] = lastI;
}
}
if (maxLength[i] > totalMaxLength) {
totalMaxLength = maxLength[i];
totalMaxIndex = i;
}
}
List<Integer> result = new LinkedList<>();
while (dividerIndex[totalMaxIndex] >= 0) {
result.add(allNums.get(totalMaxIndex));
totalMaxIndex = dividerIndex[totalMaxIndex];
}
if (totalMaxIndex >= 0) {
result.add(allNums.get(totalMaxIndex));
}
return result;
}
}