Dynamic Programming21 sections · 915 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 a∣ba | b or b∣ab | 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 a∣ba | b, then any element cc in the chain with c∣ac | a also divides bb. Transitivity holds.