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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// ============================================================================ // Author: Kenneth Perkins // Date: Nov 14, 2021 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find the largest divisible subset // ============================================================================ public class Solution { public IList<int> LargestDivisibleSubset(int[] nums) { // Sort the array Array.Sort(nums); // List array of size n var dp = new List<int>[nums.Length]; // Go through numbers var resultIndex = 0; for (int i = 0; i < nums.Length; ++i) { dp[i] = new List<int>(); // Go through numbers that come before i and determine the maximum subset for i var currentMaxIndex = i; for (int j = 0; j < i; ++j) { // Check if the two numbers satisfies the condition if ((nums[i] % nums[j] == 0 || nums[j] % nums[i] == 0) && dp[currentMaxIndex].Count < dp[j].Count) { currentMaxIndex = j; } } // Save items from max index to current dp index if (currentMaxIndex != i) { dp[i] = new List<int>(dp[currentMaxIndex]); } // Add current number to current dp index dp[i].Add(nums[i]); // Keep track of the largest subset if (dp[i].Count > dp[resultIndex].Count) { resultIndex = i; } } return dp[resultIndex]; } }// http://programmingnotes.org/ |
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]
Leave a Reply