Skip to content

368. Largest Divisible Subset

Difficulty: Medium

LeetCode Problem View on GitHub


368. Largest Divisible Subset

Medium


Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:

  • answer[i] % answer[j] == 0, or
  • answer[j] % answer[i] == 0

If there are multiple solutions, return any of them.

 

Example 1:

Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.

Example 2:

Input: nums = [1,2,4,8]
Output: [1,2,4,8]

 

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 2 * 109
  • All the integers in nums are unique.

Solution

class Solution {
    private int count[];
    private int jump[];
    public List<Integer> largestDivisibleSubset(int[] nums) {
        int n = nums.length;
        List<Integer> res = new ArrayList<>();
        count = new int[n];
        jump = new int[n];

        Arrays.sort(nums);

        for (int i = 0; i < n; i++) {
            count[i] = 1;
            jump[i] = -1;
            for (int j = i - 1; j >= 0; j--) {
                if (nums[i] % nums[j] == 0) {
                    if (count[j] + 1 > count[i]) {
                        count[i] = count[j] + 1;
                        jump[i] = j;
                    } 
                }
            }
        }
        int maxi = Integer.MIN_VALUE, idx = -1;
        for (int i = 0; i < n; i++) {
            if (count[i] > maxi) {
                maxi = count[i];
                idx = i;
            }
        }
        while (idx != -1) {
            res.add(nums[idx]);
            idx = jump[idx];
        }
        return res;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here