368. Largest divisible subset

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.