Sponsored
Sponsored
This approach utilizes dynamic programming along with sorting to find the largest subset where each pair of elements is divisible by the other. The core idea is to sort the array, then use a dynamic programming array to keep track of the size of the largest divisible subset that ends at each element. We also maintain a path array to help reconstruct the subset.
Time Complexity: O(n^2), where n is the number of elements in the input set due to the nested loop.
Space Complexity: O(n), for arrays used to store intermediate results.
1#include <stdio.h>
2#include <stdlib.h>
3
4int* largestDivisibleSubset(int* nums, int numsSize, int* returnSize) {
5 if (numsSize == 0) {
6 *returnSize = 0;
7 return NULL;
8 }
9 qsort(nums, numsSize, sizeof(int), compare);
10 int *dp = (int *)malloc(sizeof(int) * numsSize);
11 int *previous = (int *)malloc(sizeof(int) * numsSize);
12 int maxSize = 0, maxIndex = -1;
13 for (int i = 0; i < numsSize; i++) {
14 dp[i] = 1;
15 previous[i] = -1;
16 for (int j = 0; j < i; j++) {
17 if (nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1) {
18 dp[i] = dp[j] + 1;
19 previous[i] = j;
20 }
21 }
22 if (dp[i] > maxSize) {
23 maxSize = dp[i];
24 maxIndex = i;
25 }
26 }
27 int *result = (int *)malloc(sizeof(int) * maxSize);
28 int pointer = maxIndex;
29 *returnSize = maxSize;
30 for (int k = maxSize - 1; k >= 0; k--) {
31 result[k] = nums[pointer];
32 pointer = previous[pointer];
33 }
34 free(dp);
35 free(previous);
36 return result;
37}
38
39int compare(const void *a, const void *b) {
40 return (*(int*)a - *(int*)b);
41}
This C solution first checks if the input size is zero and returns an empty subset in that case. Otherwise, it sorts the numbers using qsort for processing. It uses a dynamic array, dp
, where dp[i]
indicates the length of the largest subset that ends with nums[i]
. Another array, previous
, tracks the path for reconstructing the subset. The nested for-loops store values in dp
by checking divisibility and update the maxSize
and maxIndex
. Finally, the subset is reconstructed from previous
and returned.
This approach leverages backtracking with pruning to explore subsets and constrain exploration using the divisibility constraint. It uses a sorted array to systematically explore subsets and prune paths early when constraints are no longer satisfied, allowing potentially faster exploration compared to the dynamic programming approach, especially in tightly constrained subsets.
Time and space complexities are challenging to define precisely for a backtracking solution as they depend on many factors including input distribution.
1
...