Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 368 Largest Divisible Subset - The LIS Connection

Hidden pattern

Here's the observation: if you sort the array, then for any chain a1,a2,...,aka_1, a_2, ..., a_k where each divides the next, you only need to check adjacent pairs. Why? If aa divides bb and bb divides cc, then aa divides cc. Divisibility is transitive.

So after sorting, this becomes LIS where the condition is "divides" instead of "less than". dp[i]dp[i] = length of longest divisible chain ending at index ii. The formula: dp[i]=max(dp[j]+1)dp[i] = \max(dp[j] + 1) for all j<ij < i where nums[i]modnums[j]=0nums[i] \mod nums[j] = 0.