Skip to content

Commit 9f1e2bf

Browse files
authored
Create Largest Divisible Subset
1 parent ce2b0f3 commit 9f1e2bf

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Largest Divisible Subset

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public:
3+
vector<int> largestDivisibleSubset(vector<int>& nums)
4+
{
5+
vector<int> res;
6+
7+
int n = nums.size();
8+
9+
if(n==0)
10+
return res;
11+
sort(nums.begin(), nums.end());
12+
vector<int> div_cnt(n,1);
13+
vector<int> prev(n,-1);
14+
15+
int max_idx = 0;
16+
17+
for(int i=1;i<n;i++)
18+
{
19+
for(int j=0;j<i;j++)
20+
{
21+
if(nums[i]%nums[j] == 0)
22+
{
23+
if(div_cnt[i] < div_cnt[j]+1)
24+
{
25+
div_cnt[i] = div_cnt[j]+1;
26+
prev[i] = j;
27+
}
28+
}
29+
}
30+
if(div_cnt[max_idx] < div_cnt[i])
31+
max_idx = i;
32+
}
33+
34+
while(max_idx >= 0)
35+
{
36+
res.push_back(nums[max_idx]);
37+
max_idx = prev[max_idx];
38+
}
39+
reverse(res.begin(), res.end());
40+
return res;
41+
}
42+
};

0 commit comments

Comments
 (0)