The Wayback Machine - https://web.archive.org/web/20240703214509/https://www.geeksforgeeks.org/subset-no-pair-sum-divisible-k/
Open In App

Subset with no pair sum divisible by K

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Examples : 

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.

Implementation:

C++




// C++ program to get size of subset whose
// each pair sum is not divisible by K
#include <bits/stdc++.h>
using namespace std;
  
// Returns maximum size of subset with no pair
// sum divisible by K
int subsetPairNotDivisibleByK(int arr[], int N,
                                         int K)
{
    // Array for storing frequency of modulo
    // values
    int f[K];
    memset(f, 0, sizeof(f));
  
    // Fill frequency array with values modulo K
    for (int i = 0; i < N; i++)
        f[arr[i] % K]++;
  
    //  if K is even, then update f[K/2]
    if (K % 2 == 0)
        f[K/2] = min(f[K/2], 1);
  
    // Initialize result by minimum of 1 or
    // count of numbers giving remainder 0
    int res = min(f[0], 1);
  
    // Choose maximum of count of numbers
    // giving remainder i or K-i
    for (int i = 1; i <= K/2; i++)
        res += max(f[i], f[K-i]);
  
    return res;
}
  
//  Driver code to test above methods
int main()
{
    int arr[] = {3, 7, 2, 9, 1};
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
    cout << subsetPairNotDivisibleByK(arr, N, K);
    return 0;
}


Java




// Java program to get size of subset whose
// each pair sum is not divisible by K
import java.util.Arrays;
  
class Test {
      
    // Returns maximum size of subset with no pair
    // sum divisible by K
    static int subsetPairNotDivisibleByK(int arr[], 
                                      int N, int K)
    {
          
        // Array for storing frequency of modulo
        // values
        int f[] = new int[K];
        Arrays.fill(f, 0);
      
        // Fill frequency array with values modulo K
        for (int i = 0; i < N; i++)
            f[arr[i] % K]++;
      
        // if K is even, then update f[K/2]
        if (K % 2 == 0)
            f[K/2] = Math.min(f[K/2], 1);
      
        // Initialize result by minimum of 1 or
        // count of numbers giving remainder 0
        int res = Math.min(f[0], 1);
      
        // Choose maximum of count of numbers
        // giving remainder i or K-i
        for (int i = 1; i <= K/2; i++)
            res += Math.max(f[i], f[K-i]);
      
        return res;
    }
      
    // Driver method
    public static void main(String[] args)
    {
          
        int arr[] = {3, 7, 2, 9, 1};
        int N = arr.length;
        int K = 3;
          
        System.out.print(subsetPairNotDivisibleByK(
                                         arr, N, K));
    }
}
  
// This code is contributed by Anant Agarwal.


Python3




# Python3 program to get size of
# subset whose each pair sum is
# not divisible by K
  
# Returns maximum size of subset 
# with no pair sum divisible by K
def subsetPairNotDivisibleByK(arr, N, K):
  
    # Array for storing frequency 
    # of modulo values
    f = [0 for i in range(K)]
  
    # Fill frequency array with
    # values modulo K
    for i in range(N):
        f[arr[i] % K] += 1
  
    # if K is even, then update f[K/2]
    if (K % 2 == 0):
        f[K//2] = min(f[K//2], 1)
  
    # Initialize result by minimum of 1 or
    # count of numbers giving remainder 0
    res = min(f[0], 1)
  
    # Choose maximum of count of numbers
    # giving remainder i or K-i
    for i in range(1,(K // 2) + 1):
        res += max(f[i], f[K - i])
  
    return res
      
# Driver Code
arr = [3, 7, 2, 9, 1]
N = len(arr)
K = 3
print(subsetPairNotDivisibleByK(arr, N, K))
  
# This code is contributed by Anant Agarwal.


C#




// C# program to get size of subset whose
// each pair sum is not divisible by K
using System;
  
class Test {
      
    // Returns maximum size of subset 
    // with no pair sum divisible by K
    static int subsetPairNotDivisibleByK(int []arr, 
                                         int N, int K)
    {
        // Array for storing 
        // frequency of modulo values
        int []f = new int[K];
        for(int i = 0; i < K; i++)
        f[i] = 0;
          
      
        // Fill frequency array with values modulo K
        for (int i = 0; i < N; i++)
            f[arr[i] % K]++;
      
        // if K is even, then update f[K/2]
        if (K % 2 == 0)
            f[K/2] = Math.Min(f[K/2], 1);
      
        // Initialize result by minimum of 1 or
        // count of numbers giving remainder 0
        int res = Math.Min(f[0], 1);
      
        // Choose maximum of count of numbers
        // giving remainder i or K-i
        for (int i = 1; i <= K/2; i++)
            res += Math.Max(f[i], f[K-i]);
      
        return res;
    }
      
    // Driver method
    public static void Main()
    {
        int []arr = {3, 7, 2, 9, 1};
        int N = arr.Length;
        int K = 3;
          
        // Function calling
        Console.Write(subsetPairNotDivisibleByK(arr, N, K));
    }
}
  
// This code is contributed by nitin mittal.


PHP




<?php 
// PHP program to get size of subset whose
// each pair sum is not divisible by K
  
// Returns maximum size of subset with 
// no pair sum divisible by K
function subsetPairNotDivisibleByK(&$arr, $N, $K)
{
    // Array for storing frequency of 
    // modulo values
    $f = array_fill(0, $K, NULL);
  
    // Fill frequency array with
    // values modulo K
    for ($i = 0; $i < $N; $i++)
        $f[$arr[$i] % $K]++;
  
    // if K is even, then update f[K/2]
    if ($K % 2 == 0)
        $f[$K / 2] = min($f[$K / 2], 1);
  
    // Initialize result by minimum of 1 or
    // count of numbers giving remainder 0
    $res = min($f[0], 1);
  
    // Choose maximum of count of numbers
    // giving remainder i or K-i
    for ($i = 1; $i <= $K / 2; $i++)
        $res += max($f[$i], $f[$K - $i]);
  
    return $res;
}
  
// Driver Code
$arr = array(3, 7, 2, 9, 1);
$N = sizeof($arr);
$K = 3;
echo subsetPairNotDivisibleByK($arr, $N, $K);
  
// This code is contributed by ita_c
?>


Javascript




<script>
  
// Javascript program to get size of subset whose
// each pair sum is not divisible by K
      
    // Returns maximum size of subset with no pair
    // sum divisible by K
    function subsetPairNotDivisibleByK(arr,N,K)
    {
        // Array for storing frequency of modulo
        // values
        let f = new Array(K);
        for(let i=0;i<K;i++)
        {
            f[i]=0;
        }
          
          
        
        // Fill frequency array with values modulo K
        for (let i = 0; i < N; i++)
            f[arr[i] % K]++;
        
        // if K is even, then update f[K/2]
        if (K % 2 == 0)
            f[K/2] = Math.min(f[K/2], 1);
        
        // Initialize result by minimum of 1 or
        // count of numbers giving remainder 0
        let res = Math.min(f[0], 1);
        
        // Choose maximum of count of numbers
        // giving remainder i or K-i
        for (let i = 1; i <= K/2; i++)
            res += Math.max(f[i], f[K-i]);
        
        return res;
    }
      
    let arr=[3, 7, 2, 9, 1];
    let N = arr.length;
    let K = 3;
    document.write(subsetPairNotDivisibleByK(
                                         arr, N, K));
      
    // This code is contributed by avanitrachhadiya2155
  
</script>


Output

3

Time Complexity: O(N + K) 
Auxiliary Space: O(K)

 



Previous Article
Next Article

Similar Reads

Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
Given an array of N integers, the task is to find a non-empty subset such that the sum of elements of the subset is divisible by N. Output any such subset with its size and the indices(1-based indexing) of elements in the original array if it exists. Prerequisites: Pigeonhole PrincipleExamples: Input: arr[] = { 2, 3, 7, 1, 9 } Output: 2 1 2 The req
8 min read
Sum of maximum and minimum of Kth subset ordered by increasing subset sum
Given an integer N and a set of all non-negative powers of N as S = {N0, N1, N2, N3, ... }, arrange all non-empty subsets of S in increasing order of subset-sum. The task is to find the sum of the greatest and smallest elements of the Kth subset from that ordering. Examples: Input: N = 4, K = 3Output: 5Explanation: S = {1, 4, 16, 64, ...}.Therefore
7 min read
Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might not contribute to any of the partition. Examples: In
15+ min read
Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 min read
Minimum Subset sum difference problem with Subset partitioning
Given a set of N integers with up to 40 elements, the task is to partition the set into two subsets of equal size (or the closest possible), such that the difference between the sums of the subsets is minimized. If the size of the set is odd, one subset will have one more element than the other. If the size is even, both subsets will have the same
13 min read
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K). Examples: Input: arr[] = {2, 8, 6, 5, 3},
7 min read
Maximum size of subset such that product of all subset elements is a factor of N
Given an integer N and an array arr[] having M integers, the task is to find the maximum size of the subset such that the product of all elements of the subset is a factor of N. Examples: Input: N = 12, arr[] = {2, 3, 4}Output: 2Explanation: The given array 5 subsets such that the product of all elements of the subset is a factor of 12. They are {2
6 min read
Find maximum subset-sum divisible by D by taking at most K elements from given array
Given an array A[] of size N, and two numbers K and D, the task is to calculate the maximum subset-sum divisible by D possible by taking at most K elements from A. Examples: Input: A={11, 5, 5, 1, 18}, N=5, K=3, D=7Output:28Explanation:The subset {5, 5, 18} gives the maximum sum=(5+5+18)=28 that is divisible by 7 and also has contains atmost 3 elem
11 min read
Subset with sum divisible by m
Given a set of non-negative distinct integers, and a value m, determine if there is a subset of the given set with sum divisible by m. Input Constraints Size of set i.e., n &lt;= 1000000, m &lt;= 1000Examples: Input : arr[] = {3, 1, 7, 5}; m = 6; Output : YES Input : arr[] = {1, 6}; m = 5; Output : NO Recommended PracticeSubset with sum divisible b
15+ min read
Largest subset with sum of every pair as prime
Given an array A[], find a subset of maximum size in which sum of every pair of elements is a prime number. Print its length and the subset. Consider many queries for different arrays and maximum value of an element as 100000. Examples : Input : A[] = {2, 1, 2} Output : 2 1 2 Explanation : Here, we can only form subsets with size 1 and 2. maximum s
13 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg