Subset with no pair sum divisible by K

Subset with no pair sum divisible by K

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.

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.

# 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
import sys


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


def readints():
    return map(int, sys.stdin.readline().split())


# Driver Code
N, K = readints()
arr = list(readints())

print(subsetPairNotDivisibleByK(arr, N, K))

猜你喜欢

转载自blog.csdn.net/grllery/article/details/82777932