Skip to content

Instantly share code, notes, and snippets.

@RP-3
Last active June 13, 2020 11:52
Show Gist options
  • Save RP-3/c4e6bc5a05c4632967eb63c51fea132b to your computer and use it in GitHub Desktop.
Save RP-3/c4e6bc5a05c4632967eb63c51fea132b to your computer and use it in GitHub Desktop.
/**
* @param {number[]} nums
* @return {number[]}
*/
var largestDivisibleSubset = function(nums) {
if(!nums.length) return []; // because leetcode...
/*
Sort ascending.
We do this because if our numbers are in ascending order
and we're keeping track of a 'current' subset we're working
on, we can decide whether or not we can legally add the ith
number to the current subset just by checking if its divisble
by the biggest number added so far. E.g.,
currentSubset = [1,3,6]. Can we add 12? Yeah... since it's divisible
by 6 it's also divisible by 1 and 3 (because 1 and 3 are divisible by 6).
currentSubset = [1,3,6]. Can we add 8? Nope, because it's not divisible
by 6.
*/
nums.sort((a, b) => a - b);
const maxSize = new Array(nums.length).fill(1); // this will track the
// size of the largest subset that definitely includes nums[i];
const results = nums.map((n) => [n]); // This will store the actual
// result at each index that corresponds to the number in max size.
for(let i=1; i<nums.length; i++){ // for ever number
let bestMatchIndex = i;
for(let j=0; j<i; j++){ // look at all the previous results
if(nums[i] % nums[j] === 0){ // if this is divisible by the biggest number in that previous result
if(maxSize[j] + 1 > maxSize[i]){ // try adding it, keeping track of the best so far
maxSize[i] = maxSize[j] + 1;
bestMatchIndex = j; // this is just tracking the index of the best previous result
}
}
}
if(bestMatchIndex !== i){ // now save the actual result by copying
// the previous best result and adding the current element to it
results[i] = results[bestMatchIndex].slice().concat(nums[i]);
}
}
// Now we just search through our results array and return the
// biggest one.
let [maxLen, maxIndex] = [results[0].length, 0];
for(let i=0; i<results.length; i++){
if(results[i].length > maxLen){
[maxLen, maxIndex] = [results[i].length, i];
}
}
return results[maxIndex];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment