First the array is sorted, and then the longest sequence of the positions of each number is the longest sequence of positions before that number +1. This way you can know what the longest sequence is, but you need to know the sequence in addition to the longest sequence, so where is the other record? Because the last number does not necessarily constitute the longest sequence, it is also necessary to find the end of the longest sequence, a max, a maxpos.
So maintain four variables:
1. Cnt[len]
2. Pos[len]
3. Max
4. Maxpos
1 PublicList<integer> Largestdivisiblesubset (int[] nums) {2list<integer> res =NewArraylist<integer>();3 if(Nums.length = = 0) {4 returnRes;5 }6 Arrays.sort (nums);7 intLen =nums.length;8 int[] cnt =New int[Len];9 int[] pos =New int[Len];Ten intmax = 1; One intMaxpos = 0; A for(inti = len-1; I >= 0; i--) { -Cnt[i] = 1; - for(intj = i + 1; J < Len; J + +) { the if(Nums[j]% nums[i] = = 0 && Cnt[i] < Cnt[j] + 1) { -Cnt[i] = Cnt[j] + 1; -Pos[i] =J; - if(Cnt[i] >max) { +Max =Cnt[i]; -Maxpos =i; + } A } at } - } - while(Max > 0) { - Res.add (Nums[maxpos]); -Maxpos =Pos[maxpos]; -max--; in } - returnRes; to}
368. Largest divisible subset