Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 368 · LIS

Largest Divisible Subset

LeetCode 368 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Sorted + 'divides' is transitive ⇒ it's LIS with % instead of <.

நடுத்தரம்ArrayMathDynamic ProgrammingSorting
LeetCode இல் திற ↗

நான் Largest Divisible Subset (LeetCode 368) ஐ இப்படித் தீர்த்தேன் — LIS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

After sorting, divisibility chains like LIS: if b divides c and a divides b, then a divides c. So dp[i] = longest chain ending at nums[i] where each earlier element divides the next. Store a back-pointer so the chain itself can be rebuilt.

Approach

  1. 1

    Sort the numbers.

  2. 2

    dp[i] = 1 initially; prev[i] = -1.

  3. 3

    For each j < i with nums[i] % nums[j] == 0, extend if dp[j] + 1 beats dp[i] and remember j.

  4. 4

    Track the index of the longest chain.

  5. 5

    Follow prev pointers back from that index and reverse.

நான் எப்படித் தீர்த்தேன்

LIS with back-pointersPythonO(n²) time · O(n) space
class Solution:
    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
        #longest divisible subsequence 
        #print lis
        nums.sort()
        n = len(nums)
        prev=[-1]*n
        dp=[1]*n
        max_index=0
        for i in range(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]>dp[max_index]:
                    max_index=i
        res=[]
        while max_index!=-1:
            res.append(nums[max_index])
            max_index=prev[max_index]
        return res[::-1]
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Largest Divisible Subset — அடிக்கடி கேட்கப்படும் கேள்விகள்

Largest Divisible Subset பின்னாலுள்ள intuition என்ன?

After sorting, divisibility chains like LIS: if b divides c and a divides b, then a divides c. So dp[i] = longest chain ending at nums[i] where each earlier element divides the next. Store a back-pointer so the chain itself can be rebuilt.

Largest Divisible Subset (LeetCode 368) ஐ எப்படித் தீர்ப்பது?

1. Sort the numbers. 2. dp[i] = 1 initially; prev[i] = -1. 3. For each j < i with nums[i] % nums[j] == 0, extend if dp[j] + 1 beats dp[i] and remember j. 4. Track the index of the longest chain. 5. Follow prev pointers back from that index and reverse.

Largest Divisible Subset இன் time மற்றும் space complexity என்ன?

Time: O(n²). Space: O(n). (Accepted approach: LIS with back-pointers.)

Largest Divisible Subset இல் பொதுவான தவறுகள் என்ன?

Sorting first is what makes checking only the last element enough. Several answers can be valid — any longest chain is accepted.