Largest Divisible Subset LeetCode solution in C++
1class Solution {2public:3vector<int> largestDivisibleSubset(vector<int> &nums) {4int n = nums.size();5sort(nums.begin(), nums.end());67vector<int> ans;8for (int i = 0; i < n; i++) {9vector<int> tmp;10tmp.push_back(nums[i]);1112// Checking the prev one13int j = i - 1;14while (j >= 0) {15if (tmp.back() % nums[j] == 0) tmp.push_back(nums[j]);1617j--;18}1920// Reversing the order to make it in increasing order21reverse(tmp.begin(), tmp.end());2223// Checking the forward one24j = i + 1;25while (j < n) {26if (nums[j] % tmp.back() == 0) tmp.push_back(nums[j]);2728j++;29}3031// updating the ans32if (ans.size() < tmp.size()) ans = tmp;33}3435return ans;36}37};