We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
This is a tough problem, not least because the description tacitly leads you to an exhaustive search. As you begin implementing this solution it should be clear this will take forever if the size of the set is not small. One way to reduce the size of the set it to consider the equivalence classes modulo k, instead of the elements themselves. However, this set can still have as many as k elements. The solution needs to be constructive - i.e. you must construct the largest subset. There are undoubtably faster ones, but a readable solution looks like
Create a hash table for equivalence classes (keys are i%k; values are arrays containing all elts with that modulo), then from this create a hash table with the same keys, but values are the lengths of the value arrays above.
We are only summing 2 elements at once thus only need to check pairs of our eq classes. And we know that for any i, the only elt j such that (i+j)%k = 0 is k-i. Thus we need only find which has the larger eq class: i or k-i. Find the max and sum them up.
be aware of k/2 (if k is even), and multiples of k. Each can have only 1 element in the set. This can be addressed in the hash table containing the lengths of the eq-classes.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Non-Divisible Subset
You are viewing a single comment's thread. Return to all comments →
This is a tough problem, not least because the description tacitly leads you to an exhaustive search. As you begin implementing this solution it should be clear this will take forever if the size of the set is not small. One way to reduce the size of the set it to consider the equivalence classes modulo k, instead of the elements themselves. However, this set can still have as many as k elements. The solution needs to be constructive - i.e. you must construct the largest subset. There are undoubtably faster ones, but a readable solution looks like
i%k
; values are arrays containing all elts with that modulo), then from this create a hash table with the same keys, but values are the lengths of the value arrays above.i
, the only eltj
such that(i+j)%k = 0
isk-i
. Thus we need only find which has the larger eq class:i
ork-i
. Find the max and sum them up.k/2
(ifk
is even), and multiples ofk
. Each can have only 1 element in the set. This can be addressed in the hash table containing the lengths of the eq-classes.