712816. Largest Divisible Subset

Medium

Largest Divisible Subset

Summary

Given an array A of integers, find the largest subset of A such that every pair of elements in the subset can be divided by some integer. In other words, for any two numbers a and b in the subset, there exists a number k such that a % k == 0 and b % k == 0. The goal is to find the largest such subset.

Detailed Explanation

The problem can be solved using dynamic programming. We initialize an array dp of size n, where n is the length of the input array A. Each element dp[i] represents the largest divisible subset ending at index i.

Here's a step-by-step breakdown of the solution:

  1. Initialize dp[0] = 1, since the largest divisible subset ending at the first element is just that single element.
  2. Iterate through the array from the second element to the last:
    • For each element A[i], find the maximum integer k such that A[j] % k == 0 for some j < i. This can be done using a simple linear search.
    • Update dp[i] = max(dp[i], dp[j] + 1), where j is the index of the previous element that is divisible by k.
  3. The maximum value in the dp array represents the size of the largest divisible subset.

Time complexity: O(n log n), since we perform a linear search for each element to find the maximum integer k. Space complexity: O(n), for the dynamic programming array.

Optimized Solutions

Java

View on GeeksforGeeks
public int largestDivisibleSubset(int[] A) {
    int n = A.length;
    int[] dp = new int[n];
    Arrays.fill(dp, 1);
    int maxLen = 0;
    int idx = -1;
    for (int i = 1; i < n; i++) {
        for (int j = i - 1; j >= 0; j--) {
            if (A[i] % A[j] == 0 && dp[j] + 1 > dp[i]) {
                dp[i] = dp[j] + 1;
            }
        }
        if (dp[i] > maxLen) {
            maxLen = dp[i];
            idx = i;
        }
    }
    return maxLen;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.