-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathLargest Divisible Subset.cpp
44 lines (35 loc) · 1.12 KB
/
Largest Divisible Subset.cpp
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
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<int> ans;
for(int i = 0; i < n; i++)
{
vector<int> tmp;
tmp.push_back(nums[i]);
// Checking the prev one
int j = i - 1;
while(j >= 0)
{
if(tmp.back() % nums[j] == 0)
tmp.push_back(nums[j]);
j--;
}
// Reversing the order to make it in increasing order
reverse(tmp.begin(), tmp.end());
// Checking the forward one
j = i + 1;
while(j < n)
{
if(nums[j] % tmp.back() == 0)
tmp.push_back(nums[j]);
j++;
}
// updating the ans
if(ans.size() < tmp.size())
ans = tmp;
}
return ans;
}
};