368. Largest Divisible Subset

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.

Rust Solution

struct Solution;

impl Solution {
    fn largest_divisible_subset(mut nums: Vec<i32>) -> Vec<i32> {
        let n = nums.len();
        let mut index: Vec<usize> = (0..n).collect();
        let mut size: Vec<usize> = vec![1; n];
        let mut max_size = 1;
        nums.sort_unstable();
        for i in 0..n {
            for j in 0..i {
                if nums[i] % nums[j] == 0 && size[j] + 1 > size[i] {
                    index[i] = j;
                    size[i] = size[j] + 1;
                    max_size = max_size.max(size[i]);
                }
            }
        }
        let mut res = vec![];
        for i in 0..n {
            if size[i] == max_size {
                let mut j = i;
                while index[j] != j {
                    res.push(nums[j]);
                    j = index[j];
                }
                res.push(nums[j]);
                break;
            }
        }
        res.reverse();
        res
    }
}

#[test]
fn test() {
    let nums = vec![1, 2, 3];
    let res = vec![1, 2];
    assert_eq!(Solution::largest_divisible_subset(nums), res);
    let nums = vec![1, 2, 4, 8];
    let res = vec![1, 2, 4, 8];
    assert_eq!(Solution::largest_divisible_subset(nums), res);
    let nums = vec![4, 8, 10, 240];
    let res = vec![4, 8, 240];
    assert_eq!(Solution::largest_divisible_subset(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.