Largest divisible subset

Source: Internet
Author: User

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subse T satisfies:si% SJ = 0 or sj% Si = 0.

If There is multiple solutions, return to any subset is fine.

Example 1:

Nums: [1,2,3]result: [Up] (of course, [1,3] would also be OK)

Example 2:

Nums: [1,2,4,8]result: [1,2,4,8]


Idea: Sort the array and then use Dp[i] to represent the largest collection from 0 to I. In order to get the value of dp[i], we see from i-1 to 0 whether Nums[i]% nums[j] ==0, if yes, dp[i] = max (Dp[i], dp[j]+1), because the array is sorted in descending order, so nums[j] < nums[i], And the number that can be divisible by nums[j] is also bound to be divisible by nums[i.

1  Public classSolution {2      PublicList<integer> Largestdivisiblesubset (int[] nums) {3         if(Nums = =NULL|| Nums.length = =0)return NewArraylist<integer>();4 5         intn =nums.length;6 Arrays.sort (nums);7         int[] DP =New int[n];8Arrays.fill (DP,1);9         int[] Parent =New int[n];TenArrays.fill (Parent,-1);//when a number in the parent array is-1, it means that the number itself is a collection One         intMax =1, Max_index =0;  A          for(inti =1; I < n; i++) {//Calculate Dp[i] -              for(intj = i-1; J >=0; j--) {//i > J -                 if(Nums[i]% nums[j] = =0&& Dp[i] < Dp[j] +1) {//positive distinct numbers in num theDp[i] = Dp[j] +1; -Parent[i] =J; -                     if(Dp[i] >max) { -Max =Dp[i]; +Max_index =i; -                     } +                 } A             } at         } -         returnGenresult (nums, parent, max_index); -     } -      -      PublicList<integer> Genresult (int[] Nums,int[] Parent,intMax_index) { -list<integer> result =NewArraylist<>(); in         intITER =Max_index; -          while(ITER! =-1) { to Result.add (Nums[iter]); +ITER =Parent[iter]; -         } the         returnresult; *     } $}

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: 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.