Given an array of integer numbers, we need to find maximum size of a subset such that sum of each pair of this subset is not divisible by K.
Input : arr = [3, 7, 2, 9, 1] K = 3 Output : 3 Maximum size subset whose each pair sum is not divisible by K is [3, 7, 1] because, 3+7 = 10, 3+1 = 4, 7+1 = 8 all are not divisible by 3. It is not possible to get a subset of size bigger than 3 with the above-mentioned property. Input : arr = [3, 17, 12, 9, 11, 15] K = 5 Output : 4
We can solve this problem by computing modulo of array numbers with K. if sum of two numbers is divisible by K, then if one of them gives remainder i, other will give remainder (K – i). First we store frequencies of numbers giving specific remainder in a frequency array of size K. Then we loop for all remainders i and include max(f[i], f[K – i]). Why? a subset with no pair sum divisible by K must include either elements with remainder f[i] or with remainder f[K – i]. Since we want to maximize the size of subset, we pick maximum of two sizes.
In below code array numbers with remainder 0 and remainder K/2 are handled separately. If we include more than 2 numbers with remainder 0 then their sum will be divisible by K, so we have taken at max 1 number in our consideration, same is the case with array numbers giving remainder K/2.
Time Complexity: O(N + K)
Auxiliary Space: O(K)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Largest subset with sum of every pair as prime
- Subset with sum divisible by m
- Largest divisible subset in array
- Largest divisible pairs subset
- Size of the largest divisible subset in an Array
- Triplet pair (a, b, c) such that a+b, b+c and a+c are all divisible by K
- Subarray with no pair sum divisible by K
- Check if there is any pair in a given range with GCD is divisible by k
- Minimum pair sum operations to make array each element divisible by 4
- Store duplicate keys-values pair and sort the key-value pair by key
- Probability of a random pair being the maximum weighted pair
- Pair formation such that maximum pair sum is minimized
- Pair with given product | Set 1 (Find if any pair exists)
- Number of indices pair such that element pair sum from first Array is greater than second Array
- Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]