Clean code in C++ 52ms with some comments


  • 1
    vector<int> largestDivisibleSubset(vector<int>& nums) 
    {
            int size = nums.size();
            if(!size) return vector<int>();
            sort(nums.begin(), nums.end()); //essential 
            //the maximal amount till current index and its corresponding last divisible index;
            vector<pair<int, int>> maxWithIndex(1, make_pair(1, -1)); 
            int globalMax = 1, index = 0;
            for(int i = 1; i < size; ++i)
            {
                int maxCount = 1, preIndex = -1;
                for(int j = i-1; j >=0; --j)
                {
                    if(nums[i]%nums[j]==0 && maxWithIndex[j].first>=maxCount)
                        maxCount = maxWithIndex[j].first+1, preIndex = j;
                }
                maxWithIndex.emplace_back(maxCount, preIndex);
                if(maxCount > globalMax) globalMax = maxCount, index = i; //maintain the global max
            }
            vector<int> v;
            for(int i = 0; i < globalMax; ++i, index = maxWithIndex[index].second) //ensure ascending order
                v.insert(v.begin(), nums[index]);
            return v;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.