Problem 649
Largest Divisible Subset
Medium · 20 pts · Dynamic Programming, Sorting, Math
Problem
Given a set of distinct positive integers, find the size of the largest subset in which every pair (x, y) satisfies x % y = 0 or y % x = 0. After sorting, such a subset is a chain where each element divides the next one, and divisibility is transitive. So run a longest-chain DP: best[i] = 1 + max(best[j]) over every j < i with A[i] % A[j] = 0.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1]. The values are distinct.
Output
Print the size of the largest divisible subset.
Constraints
1 <= N <= 1000; 1 <= A[i] <= 2 × 10^9; values are distinct
Example input
5 1 2 4 8 3
Example output
4
Explanation
In 1 2 4 8 3, the subset 1 2 4 8 works because each element divides the next. Adding 3 would break it (3 and 2 do not divide each other), so the answer is 4.