Leetcode 368. Largest Divisible Subset
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj == 0 or Sj % Si == 0
If there are multiple solutions, return any of them.
dp[i]
represents the size of the largest divisible subset ending with nums[i]
.#include <vector>
#include <algorithm>
std::vector<int> largestDivisibleSubset(std::vector<int>& nums) {
int n = nums.size();
if (n == 0) return {};
std::sort(nums.begin(), nums.end());
std::vector<int> dp(n, 1);
std::vector<int> prev(n, -1);
int maxSubsetSize = 1;
int maxSubsetIndex = 0;
// Fill dp and prev arrays
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
prev[i] = j;
}
}
if (dp[i] > maxSubsetSize) {
maxSubsetSize = dp[i];
maxSubsetIndex = i;
}
}
// Reconstruct the largest subset
std::vector<int> largestSubset;
for (int i = maxSubsetIndex; i >= 0; i = prev[i]) {
largestSubset.push_back(nums[i]);
if (prev[i] == i) break;
}
std::reverse(largestSubset.begin(), largestSubset.end());
return largestSubset;
}
The combined time complexity is (O(n^2)), which is dominated by the dynamic programming update steps.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?