368. Largest Divisible Subset #1525
-
Topics: Given a set of distinct positive integers
If there are multiple solutions, return any of them. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the largest subset of distinct positive integers such that every pair of elements in the subset satisfies the divisibility condition (i.e., one element divides the other). The approach involves dynamic programming (DP) to efficiently determine the longest chain of elements where each subsequent element is a multiple of the previous one. Approach
Let's implement this solution in PHP: 368. Largest Divisible Subset <?php
/**
* @param Integer[] $nums
* @return Integer[]
*/
function largestDivisibleSubset($nums) {
sort($nums);
$n = count($nums);
if ($n == 0) {
return [];
}
$dp = array_fill(0, $n, 1);
$prev = array_fill(0, $n, -1);
$max_len = 1;
$max_idx = 0;
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $i; $j++) {
if ($nums[$i] % $nums[$j] == 0) {
if ($dp[$j] + 1 > $dp[$i]) {
$dp[$i] = $dp[$j] + 1;
$prev[$i] = $j;
}
}
}
if ($dp[$i] > $max_len) {
$max_len = $dp[$i];
$max_idx = $i;
}
}
$result = [];
$idx = $max_idx;
while ($idx != -1) {
array_unshift($result, $nums[$idx]);
$idx = $prev[$idx];
}
return $result;
}
// Example usage:
$nums1 = [1, 2, 3];
print_r(largestDivisibleSubset($nums1)); // Possible outputs: [1,2] or [1,3]
$nums2 = [1, 2, 4, 8];
print_r(largestDivisibleSubset($nums2)); // Output: [1, 2, 4, 8]
?> Explanation:
This approach efficiently finds the largest divisible subset using dynamic programming and backtracking, ensuring optimal performance with a time complexity of O(n2), which is feasible given the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the largest subset of distinct positive integers such that every pair of elements in the subset satisfies the divisibility condition (i.e., one element divides the other). The approach involves dynamic programming (DP) to efficiently determine the longest chain of elements where each subsequent element is a multiple of the previous one.
Approach
dp[i]
to store the length of the largest divisible subset ending with the element at indexi
.prev[i]
to track the in…