Leetcode 368 Solution

This article provides solution to leetcode question 368 (largest-divisible-subset)

https://leetcode.com/problems/largest-divisible-subset

Solution

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        sort(nums.begin(), nums.end());

        vector<int> dp(nums.size() + 1, 1);
        vector<int> prevs(nums.size() + 1, -1);
        int max_count = 0;
        int max_count_pos = -1;

        for (int i = 0; i < nums.size(); i++)
        {
            int num = nums[i];

            for (int j = 0; j < i; j++)
            {
                if (nums[i] % nums[j] == 0)
                {
                    if (dp[i] < dp[j] + 1)
                    {
                        dp[i] = dp[j] + 1;
                        prevs[i] = j;
                    }
                }
            }

            if (max_count < dp[i])
            {
                max_count = dp[i];
                max_count_pos = i;
            }
        }

        vector<int> res;
        int curr = max_count_pos;
        while (curr != -1)
        {
            res.push_back(nums[curr]);
            curr = prevs[curr];
        }

        reverse(res.begin(), res.end());

        return res;
    }
};