Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 368 Largest Divisible Subset - Walkthrough

LIS with divisibility

Find the largest subset where every pair (a,b)(a, b) has aba | b or bab | a. Sort and apply LIS-like DP. Sort the array.

For each element, extend from any previous element that divides it. Example: [1,2,4,8,3][1, 2, 4, 8, 3] → sorted: [1,2,3,4,8][1, 2, 3, 4, 8]. DP: [1,2,2,3,4][1, 2, 2, 3, 4]. Subset: {1,2,4,8}\{1, 2, 4, 8\}. observation: if the array is sorted and aba | b, then any element cc in the chain with cac | a also divides bb. Transitivity holds.