C# || How To Find The Largest Divisible Subset In Array Using C#

The following is a module with functions which demonstrates how to find the largest divisible subset in an array using C#.


1. Largest Divisible Subset – Problem Statement

Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:

  • answer[i] % answer[j] == 0, or
  • answer[j] % answer[i] == 0

If there are multiple solutions, return any of them.

Example 1:


Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.

Example 2:


Input: nums = [1,2,4,8]
Output: [1,2,4,8]


2. Largest Divisible Subset – Solution

The following is a solution which demonstrates how to find the largest divisible subset in an array.

This solution uses Dynamic Programming to find the largest divisible subset.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


[1,2]
[1,2,4,8]

Was this article helpful?
👍 YesNo

Leave a Reply