-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargestDivisibleSubset.cpp
More file actions
49 lines (37 loc) · 1.06 KB
/
largestDivisibleSubset.cpp
File metadata and controls
49 lines (37 loc) · 1.06 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
#include <iostream>
using namespace std;
vector<int> largestDivisibleSubset(vector<int>&arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
vector<int>count(n, 1), hash(n, 0);
for(int i = 0; i < n; i++) {
hash[i] = i;
for(int prev = 0; prev < i; prev++) {
if(arr[i] % arr[prev] == 0 && 1 + count[prev] > count[i]) {
count[i] = 1 + count[prev];
hash[i] = prev;
}
}
}
int ans = -1; int lastIndex = -1;
for(int i = 0; i < n; i++) {
if(count[i] > ans){
ans = count[i];
lastIndex = i;
}
}
vector<int>temp;
temp.push_back(arr[lastIndex]);
while(lastIndex != hash[lastIndex]) {
lastIndex = hash[lastIndex];
temp.push_back(arr[lastIndex]);
}
reverse(temp.begin(), temp.end());
return temp;
}
int main() {
vector<int> arr = {0,1,16,7,8,4};
vector<int> ans = largestDivisibleSubset(arr);
cout << "The largest divisible subset length is " << ans.size() << endl;
return 0;
}