Maximum subset which has no sum of two divisible by K

后端 未结 5 950
栀梦
栀梦 2021-02-14 16:49

I am given the set {1, 2, 3, ... ,N}. I have to find the maximum size of a subset of the given set so that the sum of any 2 numbers from the subset is not divisible by a given n

5条回答
  •  忘掉有多难
    2021-02-14 17:15

    This is explanation to ABRAR TYAGI and amin k's solution.

    The approach to this solution is:

    • Create an array L with K buckets and group all the elements from the input array D into the K buckets. Each bucket L[i] contains D's elements such that ( element % K ) = i.
    • All the elements that are individually divisible by K are in L[0]. So only one of these elements (if any) can belong in our final (maximal) subset. Sum of any two of these elements is divisible by K.
    • If we add an element from L[i] to an element in L[K-i] then the sum is divisible by K. Hence we can add elements from only one of these buckets to our final set. We pick the largest bucket.

    Code: d is the array containing the initial set of numbers of size n. The goal of this code is to find the count of the largest subset of d such that the sum of no two integers is divisible by 2.

    l is an array that will contain k integers. The idea is to reduce each (element) in array d to (element % k) and save the frequency of their occurrences in array l.

    For example, l[1] contains the frequency of all elements % k = 1

    We know that 1 + (k-1) % k = 0 so either l[1] or l[k-1] have to be discarded to meet the criteria that sum of no two numbers % k should be 0.

    But as we need the largest subset of d, we choose the larger of l[1] and l[k-1]

    We loop through array l such that for (i=1; i<=k/2 && i < k-i; i++) and do the above step.

    There are two outliers. The sum of any two numbers in the l[0] group % k = 0. So add 1 if l[0] is non-zero.

    if k is even, the loop does not handle i=k/2, and using the same logic as above increment the count by one.

提交回复
热议问题