Skip to content

Commit bf75ec7

Browse files
Largest Divisible Subset
1 parent 044ea0a commit bf75ec7

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

Diff for: 13.cpp

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
3+
Largest Divisible Subset
4+
------------------------
5+
6+
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
7+
8+
Si % Sj = 0 or Sj % Si = 0.
9+
10+
If there are multiple solutions, return any subset is fine.
11+
12+
Example 1:
13+
14+
Input: [1,2,3]
15+
Output: [1,2] (of course, [1,3] will also be ok)
16+
Example 2:
17+
18+
Input: [1,2,4,8]
19+
Output: [1,2,4,8]
20+
*/
21+
22+
class Solution {
23+
public:
24+
vector<int> largestDivisibleSubset(vector<int>& nums) {
25+
int n = nums.size();
26+
sort(nums.begin(), nums.end());
27+
28+
vector<int> v, next(n, -1), count(n, -1);
29+
int x = -1;
30+
for (int i = 0; i < n; ++i) {
31+
for (int j = 0; j < i; ++j) {
32+
if (nums[i] % nums[j] != 0) continue;
33+
if (next[i] == -1 || count[j] > count[next[i]]) next[i] = j;
34+
}
35+
count[i] = (next[i] == -1) ? 1 : count[next[i]]+1;
36+
if (x == -1 || count[i] > count[x]) x = i;
37+
}
38+
39+
while (x != -1) { v.push_back(nums[x]); x = next[x]; }
40+
reverse(v.begin(), v.end());
41+
42+
return v;
43+
}
44+
};

Diff for: README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@
1313
| 9 | Is Subsequence | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/9.cpp) |
1414
| 10 | Search Insert Position | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/10.cpp) |
1515
| 11 | Sort Colors | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/11.cpp) |
16-
| 12 | Insert Delete GetRandom O(1) | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/12.cpp) |
16+
| 12 | Insert Delete GetRandom O(1) | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/12.cpp) |
17+
| 13 | Largest Divisible Subset | [Link](https://github.com/ishpreet-singh/leetcode-june-challenge/blob/master/13.cpp) |

0 commit comments

Comments
 (0)