Open In App

Maximize the number of sum pairs which are divisible by K

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of N integers and an integer K. The task is to print the maximum number of pairs(a[i]+a[j]) possible which are divisible by K. 
Note: A particular index number cannot be considered in more than one pair. 
Examples: 
 

Input: a[] = {1, 2, 2, 3, 2, 4, 10}, k =2 
Output:
The pairs are: (1, 2), (4, 5), (0, 3)
Input: a[] = {1, 2, 2, 3, 2, 4, 5}, k = 3 
Output:
 

 

Naive Approach: A naive approach is to iterate using two loops and calculate the total number of pairs whose sum is divisible by K. 

Time Complexity: O(N^2), as we will be using nested loops for traversing N*N times. Where N is the number of elements in the array.

Auxiliary Space: O(1), as we will be not using any extra space.
Efficient Approach: An efficient approach will be to use a hashing technique to solve the problem. The following steps can be followed to solve the above problem. 

  • Initially increase the hash[a[i]%k] by one for every array element.
  • Iterate in the map and get every possible hash values.
  • If the hash value is 0, then the number of pairs will be hash[0]/2.
  • After that for every hash value x, we can use the minimum of (hash[x], hash[k-x]) and use them to create pairs.
  • Subtract the number of pairs used from the hash value accordingly.

Below is the implementation of the above approach. 
 

C++




// C++ program to implement the above
// approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the number of pairs
int findMaximumPairs(int a[], int n, int k)
{
 
    // Hash-table
    unordered_map<int, int> hash;
    for (int i = 0; i < n; i++)
        hash[a[i] % k]++;
 
    int count = 0;
 
    // Iterate for all numbers less than hash values
    for (auto it : hash) {
 
        // If the number is 0
        if (it.first == 0) {
 
            // We take half since same number
            count += it.second / 2;
            if (it.first % 2 == 0)
                hash[it.first] = 0;
            else
                hash[it.first] = 1;
        }
        else {
 
            int first = it.first;
            int second = k - it.first;
 
            // Check for minimal occurrence
            if (hash[first] < hash[second]) {
                // Take the minimal
                count += hash[first];
 
                // Subtract the pairs used
                hash[second] -= hash[first];
                hash[first] = 0;
            }
            else if (hash[first] > hash[second]) {
                // Take the minimal
                count += hash[second];
 
                // Subtract the pairs used
                hash[first] -= hash[second];
                hash[second] = 0;
            }
            else {
                // Check if numbers are same
                if (first == second) {
 
                    // If same then number of pairs will be half
                    count += it.second / 2;
 
                    // Check for remaining
                    if (it.first % 2 == 0)
                        hash[it.first] = 0;
                    else
                        hash[it.first] = 1;
                }
                else {
 
                    // Store the number of pairs
                    count += hash[first];
                    hash[first] = 0;
                    hash[second] = 0;
                }
            }
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    int a[] = { 1, 2, 2, 3, 2, 4, 10 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 2;
    cout << findMaximumPairs(a, n, k);
 
    return 0;
}


Java




// Java program to implement the above
// approach
import java.util.*;
 
class GFG
{
 
// Function to maximize the number of pairs
static int findMaximumPairs(int a[], int n, int k)
{
 
    // Hash-table
    HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
    for (int i = 0; i < n; i++)
        if(hash.containsKey(a[i] % k)){
            hash.put(a[i] % k, hash.get(a[i] % k)+1);
        }
        else{
            hash.put(a[i] % k, 1);
        }
 
    int count = 0;
 
    // Iterate for all numbers less than hash values
    for (Map.Entry<Integer,Integer> it : hash.entrySet()){
 
        // If the number is 0
        if (it.getKey() == 0) {
 
            // We take half since same number
            count += it.getValue() / 2;
            if (it.getKey() % 2 == 0)
                hash.put(it.getKey(), 0);
            else
                hash.put(it.getKey(), 1);
        }
        else {
 
            int first = it.getKey();
            int second = k - it.getKey();
 
            // Check for minimal occurrence
            if (hash.get(first) < hash.get(second))
            {
                 
                // Take the minimal
                count += hash.get(first);
 
                // Subtract the pairs used
                hash.put(second, hash.get(second)-hash.get(first));
                hash.put(first, 0);
            }
            else if (hash.get(first) > hash.get(second))
            {
                 
                // Take the minimal
                count += hash.get(second);
 
                // Subtract the pairs used
                hash.put(first, hash.get(first)-hash.get(second));
                hash.put(second, 0);
            }
            else
            {
                // Check if numbers are same
                if (first == second) {
 
                    // If same then number of pairs will be half
                    count += it.getValue() / 2;
 
                    // Check for remaining
                    if (it.getKey() % 2 == 0)
                        hash.put(it.getKey(), 0);
                    else
                        hash.put(it.getKey(), 1);
                }
                else {
 
                    // Store the number of pairs
                    count += hash.get(first);
                    hash.put(first, 0);
                    hash.put(second, 0);
                }
            }
        }
    }
 
    return count;
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = { 1, 2, 2, 3, 2, 4, 10 };
    int n = a.length;
    int k = 2;
    System.out.print(findMaximumPairs(a, n, k));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to implement
# the above approach
 
# Function to maximize the
# number of pairs
def findMaximumPairs(a, n, k) :
 
    # Hash-table
    hash = {};
    for i in range(n) :
        if a[i] % k not in hash :
            hash[a[i] % k] = 0
         
        hash[a[i] % k] += 1
 
    count = 0;
 
    # Iterate for all numbers less
    # than hash values
    for keys,values in hash.items() :
 
        # If the number is 0
        if (keys == 0) :
 
            # We take half since same number
            count += values // 2;
            if (keys % 2 == 0) :
                hash[keys] = 0;
            else :
                hash[keys] = 1;
                 
        else :
 
            first = keys;
            second = k -keys;
 
            # Check for minimal occurrence
            if (hash[first] < hash[second]) :
                 
                # Take the minimal
                count += hash[first];
 
                # Subtract the pairs used
                hash[second] -= hash[first];
                hash[first] = 0;
             
            elif (hash[first] > hash[second]) :
                 
                # Take the minimal
                count += hash[second];
 
                # Subtract the pairs used
                hash[first] -= hash[second];
                hash[second] = 0;
             
            else :
                 
                # Check if numbers are same
                if (first == second) :
 
                    # If same then number of pairs
                    # will be half
                    count += values // 2;
 
                    # Check for remaining
                    if (keys % 2 == 0) :
                        hash[keys] = 0;
                    else :
                        hash[keys] = 1;
                 
                else :
 
                    # Store the number of pairs
                    count += hash[first];
                    hash[first] = 0;
                    hash[second] = 0;
                     
    return count;
 
# Driver code
if __name__ == "__main__" :
 
    a = [ 1, 2, 2, 3, 2, 4, 10 ];
    n = len(a)
    k = 2;
    print(findMaximumPairs(a, n, k));
 
# This code is contributed by Ryuga


C#




using System;
using System.Collections.Generic;
 
public class MainClass {
    public static int FindMaximumPairs(int[] a, int n, int k) {
        // Hash-table
        Dictionary<int, int> hash = new Dictionary<int, int>();
        for (int i = 0; i < n; i++) {
            if (!hash.ContainsKey(a[i] % k)) {
                hash[a[i] % k] = 0;
            }
            hash[a[i] % k]++;
        }
 
        int count = 0;
 
        // Iterate for all numbers less than hash values
        foreach (KeyValuePair<int, int> kvp in new Dictionary<int, int>(hash)) {
            int keys = kvp.Key;
            int values = kvp.Value;
 
            // If the number is 0
            if (keys == 0) {
                // We take half since same number
                count += values / 2;
                if (keys % 2 == 0) {
                    hash[keys] = 0;
                } else {
                    hash[keys] = 1;
                }
            } else {
                int first = keys;
                int second = k - keys;
 
                // Check for minimal occurrence
                if (hash[first] < hash[second]) {
                    // Take the minimal
                    count += hash[first];
 
                    // Subtract the pairs used
                    hash[second] -= hash[first];
                    hash[first] = 0;
                } else if (hash[first] > hash[second]) {
                    // Take the minimal
                    count += hash[second];
 
                    // Subtract the pairs used
                    hash[first] -= hash[second];
                    hash[second] = 0;
                } else {
                    // Check if numbers are same
                    if (first == second) {
                        // If same then number of pairs will be half
                        count += values / 2;
 
                        // Check for remaining
                        if (keys % 2 == 0) {
                            hash[keys] = 0;
                        } else {
                            hash[keys] = 1;
                        }
                    } else {
                        // Store the number of pairs
                        count += hash[first];
                        hash[first] = 0;
                        hash[second] = 0;
                    }
                }
            }
        }
 
        return count;
    }
 
    public static void Main() {
        int[] a = { 1, 2, 2, 3, 2, 4, 10 };
        int n = a.Length;
        int k = 2;
        Console.WriteLine(FindMaximumPairs(a, n, k));
    }
}


Javascript




<script>
// Javascript program to implement the above
// approach
 
// Function to maximize the number of pairs
function findMaximumPairs(a, n, k) {
 
    // Hash-table
    let hash = new Map();
    for (let i = 0; i < n; i++) {
        if (hash.has(a[i] % k)) {
            hash.set(a[i] % k, hash.get(a[i] % k) + 1)
        } else {
            hash.set(a[i] % k, 1)
        }
    }
 
    let count = 0;
 
    // Iterate for all numbers less than hash values
    for (let it of hash) {
 
        // If the number is 0
        if (it[0] == 0) {
 
            // We take half since same number
            count += Math.floor(it[1] / 2);
            if (it[0] % 2 == 0)
                hash.set(it[0], 0);
            else
                hash.set(it[0], 1);
        }
        else {
 
            let first = it[0];
            let second = k - it[0];
 
            // Check for minimal occurrence
            if (hash.get(first) < hash.get(second)) {
                // Take the minimal
                count += hash.get(first);
 
                // Subtract the pairs used
                hash.set(second, hash.get(second) - hash.get(first));
                hash.set(first, 0);
            }
            else if (hash.get(first) > hash.get(second)) {
                // Take the minimal
                count += hash.get(second);
 
                // Subtract the pairs used
                hash.set(first, hash.get(first) - hash.get(second));
                hash.set(second, 0);
            }
            else {
                // Check if numbers are same
                if (first == second) {
 
                    // If same then number of pairs will be half
                    count += Math.floor(it[1] / 2);
 
                    // Check for remaining
                    if (it[0] % 2 == 0)
                        hash.set(it[0], 0);
                    else
                        hash.set(it[0], 1);
                }
                else {
 
                    // Store the number of pairs
                    count += hash.get(first);
                    hash.set(first, 0);
                    hash.set(second, 0);
                }
            }
        }
    }
 
    return count;
}
 
// Driver code
let a = [1, 2, 2, 3, 2, 4, 10];
let n = a.length;
let k = 2;
document.write(findMaximumPairs(a, n, k));
 
// This code is contributed by _saurabh_jaiswal
</script>


Output: 

3

 

Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of elements in the array.

Auxiliary Space: O(N), as we are using extra space for the map. Where N is the number of elements in the array.
 



Similar Reads

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]
Given an array arr[] of N integers, the task is to find the count of unordered index pairs (i, j) such that i != j and 0 &lt;=i &lt; j &lt; N and either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]. Examples: Input: arr[] = {2, 4} Output: 1 (0, 1) is the only index pair possible. Input: arr[] = {3, 2, 4, 2, 6} Output: 6 Possible p
7 min read
Find permutation of n which is divisible by 3 but not divisible by 6
Given an integer [Tex]n [/Tex]. The task is to find another integer which is permutation of n, divisible by 3 but not divisible by 6. Given that n is divisible by 6. If no such permutation is possible print -1. Examples: Input: n = 336 Output: 363 Input: n = 48 Output: -1 For a number to be divisible by 6, it must be divisible by 3 as well as 2, me
5 min read
Count of pairs of Array elements which are divisible by K when concatenated
Given an array arr[] and an integer K, the task is to count the pair of indices (i, j) such that i !=j and concatenation of a[i] and a[j] is divisible by K. Example: Input: arr[] = [4, 5, 2], K = 2 Output: 4 Explanation: All possible concatenations are {45, 42, 54, 52, 24, 25}. Out of these, the numbers divisible by 2 are {42, 52, 24, 54}. Therefor
9 min read
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND
Given an array arr[] consisting of N positive integers, replace pairs of array elements whose Bitwise AND exceeds Bitwise XOR values by their Bitwise AND value. Finally, count the maximum number of such pairs that can be generated from the array. Examples: Input: arr[] = {12, 9, 15, 7}Output: 2Explanation:Step 1: Select the pair {12, 15} and replac
9 min read
Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR
Given an array arr[] of size N, the task is to replace a pair of array elements whose Bitwise XOR is even by their Bitwise XOR. Repeat the above step as long as possible. Finally, print the count of such operations performed on the array Examples: Input: arr[] = { 4, 6, 1, 3 }Output: 3Explanation:Step 1: Remove the pair (4, 6) and replace them by t
11 min read
Maximize array sum by replacing equal adjacent pairs by their sum and X respectively
Given two integers N and X which denotes the size of an array arr[] and the initial value of all the array elements respectively, the task is to find the maximum sum possible from the given array after performing the following operation any number of times. Choose any valid index i for which arr[i] = arr[i + 1] and update arr[i] = arr[i] + arr[i +
6 min read
Count number of pairs in array having sum divisible by K | SET 2
Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K.Examples: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 There are five pairs possible whose sum Is divisible by '4' i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3)Input : A[] = {5, 9, 36, 74, 52, 31, 42}, K = 3 Out
6 min read
Number of pairs from the first N natural numbers whose sum is divisible by K
Given the integer values of N and K. The task is to find the number of pairs from the set of natural numbers up to N{1, 2, 3......N-1, N} whose sum is divisible by K. Note : 1 &lt;= K &lt;= N &lt;= 10^6.Examples: Input : N = 10, K = 5 Output : 9 Explanation : The possible pairs whose sum is divisible by 5 are (1, 4), (1, 9), (6, 4), (6, 9), (2, 3),
14 min read
Split a number as sum of K numbers which are not divisible by K
Given two numbers N and K, the task is to split this number into K positive integers such that their sum is equal to N and none of these K integers is a multiple of K. Note: N&gt;=2 Examples: Input: N = 10, K = 3 Output: 1, 1, 8Input: N = 18, K = 3 Output:1, 1, 16 Approach: To split N into K numbers, we need to approach the problem by the following
5 min read
Check if a large number is divisible by a number which is a power of 2
Given a large number in the form of a string str and a number K, the task is to check if the number formed by string str is divisible by the K or not, where K is a power of 2. Examples: Input: str = "5426987513245621541524288", num = 64 Output: Yes Explanation: Since log2(64) = 6, so the number formed by the last 6 digits from the string str is div
7 min read
Practice Tags :