Skip to content

Commit 61b4c46

Browse files
committed
Sync LeetCode submission Runtime - 131 ms (98.87%), Memory - 18.8 MB (17.14%)
1 parent 828aa06 commit 61b4c46

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p>
2+
3+
<ul>
4+
<li><code>answer[i] % answer[j] == 0</code>, or</li>
5+
<li><code>answer[j] % answer[i] == 0</code></li>
6+
</ul>
7+
8+
<p>If there are multiple solutions, return any of them.</p>
9+
10+
<p>&nbsp;</p>
11+
<p><strong class="example">Example 1:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> nums = [1,2,3]
15+
<strong>Output:</strong> [1,2]
16+
<strong>Explanation:</strong> [1,3] is also accepted.
17+
</pre>
18+
19+
<p><strong class="example">Example 2:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> nums = [1,2,4,8]
23+
<strong>Output:</strong> [1,2,4,8]
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
31+
<li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li>
32+
<li>All the integers in <code>nums</code> are <strong>unique</strong>.</li>
33+
</ul>
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Approach 1: Dynamic Programming
2+
3+
# Time: O(n^2)
4+
# Space: O(n^2)
5+
6+
class Solution:
7+
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
8+
subsets = {-1: set()}
9+
10+
for num in sorted(nums):
11+
subsets[num] = max([subsets[k] for k in subsets if num % k == 0], key = len) | {num}
12+
13+
return list(max(subsets.values(), key=len))
14+

0 commit comments

Comments
 (0)