Skip to content

Commit 906b3f2

Browse files
authored
Merge pull request #197 from sailok/master
Adding Leetcode Problem 368. Largest Divisible Subset.
2 parents 77f596e + e4c250d commit 906b3f2

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
2+
3+
# Si % Sj = 0 or Sj % Si = 0.
4+
5+
# If there are multiple solutions, return any subset is fine.
6+
7+
# Example 1:
8+
9+
# Input: [1,2,3]
10+
11+
# Output: [1,2] (of course, [1,3] will also be ok)
12+
13+
# Example 2:
14+
15+
# Input: [1,2,4,8]
16+
17+
# Output: [1,2,4,8]
18+
class Solution:
19+
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
20+
if len(nums) < 2:
21+
return nums
22+
23+
#creating a monotonic sequence of list
24+
nums.sort()
25+
26+
dp = [1]*len(nums)
27+
max_ind = 0
28+
29+
#dp pass using the following condition
30+
for i in range(1, len(nums)):
31+
for j in range(i):
32+
if nums[i]%nums[j] == 0:
33+
dp[i] = max(dp[i], dp[j] + 1)
34+
if dp[max_ind] < dp[i]:
35+
max_ind = i
36+
37+
res = []
38+
res.append(nums[max_ind])
39+
40+
prev = nums[max_ind]
41+
42+
#reconstructing the sequence by iterating backwards
43+
for i in range(max_ind - 1, -1, -1):
44+
if dp[i] > 0 and dp[max_ind]-1 == dp[i] and prev%nums[i] == 0:
45+
res.append(nums[i])
46+
prev = nums[i]
47+
max_ind = i
48+
49+
res.reverse()
50+
return res

0 commit comments

Comments
 (0)