Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 6, 2025 22:28
Show Gist options
  • Save Ifihan/619714820a5ddaa139654407c1e70d57 to your computer and use it in GitHub Desktop.
Save Ifihan/619714820a5ddaa139654407c1e70d57 to your computer and use it in GitHub Desktop.
Largest Divisible Subset

Question

Approach

First, I sorted the input list nums to ensure that for any two elements nums[i] and nums[j], where i > j, nums[i] % nums[j] is easy to check. I then used a dp array where dp[i] stores the size of the largest divisible subset ending at index i. I also tracked the prev index to reconstruct the subset at the end. I returned the largest subset by backtracking from the maximum value in dp.

Implementation

class Solution:
    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
        if not nums:
            return []

        nums.sort()
        n = len(nums)
        dp = [1] * n
        prev = [-1] * n

        max_len = 1
        max_index = 0

        for i in range(1, n):
            for j in range(i):
                if nums[i] % nums[j] == 0 and dp[j] + 1 > dp[i]:
                    dp[i] = dp[j] + 1
                    prev[i] = j
            if dp[i] > max_len:
                max_len = dp[i]
                max_index = i

        result = []
        while max_index != -1:
            result.append(nums[max_index])
            max_index = prev[max_index]

        return result[::-1]

Complexities

  • Time: O(n^2)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment