-
Notifications
You must be signed in to change notification settings - Fork 0
/
Largest divisible subset
78 lines (64 loc) · 2.24 KB
/
Largest divisible subset
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
76
77
78
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
# Sol 1
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> list=new ArrayList<>();
Arrays.sort(nums);
int maxDivCount=0;
int index=0;
for(int i=0; i<nums.length; i++){
int divCount=0;
for(int j=i; j<nums.length; j++){
if(nums[j]%nums[i]==0){
divCount++;
}
}
if(divCount>maxDivCount){
maxDivCount=divCount;
index=i;
}
divCount=0;
}
for(int i=0; i<nums.length; i++){
if(nums[i]%nums[index]==0){
list.add(nums[i]);
}
}
return list;
}
}
# Status Solved. Won't work if the array starts with 1.
# Sol 2
int divCount[] = new int[arr.length];
// we will always have atleast one
// element divisible by itself
Arrays.fill(divCount, 1);
// maintain the index of the last increment
int prev[] = new int[arr.length];
Arrays.fill(prev, -1);
// index at which last increment happened
int max_ind = 0;
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < i; j++) {
// only increment the maximum index if
// this iteration will increase it
if (arr[i] % arr[j] == 0 &&
divCount[i] < divCount[j] + 1) {
prev[i] = j;
divCount[i] = divCount[j] + 1;
}
}
// Update last index of largest subset if size
// of current subset is more.
if (divCount[i] > divCount[max_ind])
max_ind = i;
}
// Print result
int k = max_ind;
while (k >= 0) {
System.out.print(arr[k] + " ");
k = prev[k];
}
# Status copied. I'll never be able to come up with an algo like this.