forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0368.cpp
More file actions
executable file
·35 lines (30 loc) · 808 Bytes
/
LC0368.cpp
File metadata and controls
executable file
·35 lines (30 loc) · 808 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/largest-divisible-subset/
Time: O(n²)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n);
if (nums.empty())
return {};
sort(nums.begin(), nums.end());
// dynamic programming
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
if (nums[i] % nums[j] == 0)
dp[i] = max(dp[j] + 1, dp[i]);
// backtrack
int pos = distance(dp.begin(), max_element(dp.begin(), dp.end()));
vector<int> subset = {nums[pos]};
for (int i = n - 1; i >= 0; i--)
if (subset.back() % nums[i] == 0 && dp[i] == dp[pos] - 1) {
pos = i;
subset.push_back(nums[i]);
}
return subset;
}
};