2

Given an array A of N elements. We need to find the number of subsets (with repetition of numbers allowed) such that the number of elements in the subset is P and the sum of those P elements is divisible by M.

N can be upto 10^5

P can be upto 10^5

M can be upto 10

Elements in the array can be upto 10^9

What I thought: I thought of generating subset sum using dynamic programming starting from sum=M till sum=P*max(A) and then find all the subset sums which are divisible by M but it will surely be too unefficient. Any idea how can I solve this problem?

Subset sum (with repetition allowed) algorithm can be seen here: https://tutorialspoint.dev/algorithm/dynamic-programming-algorithms/ways-sum-n-using-array-elements-repetition-allowed

Even small hints about the approach would be appreciated

  • There doesn't seem to be a question in your post. You have a problem, which looks like "homework" and you want someone to write the code for you? If so, that's not what StackOverflow is for. Check the question guidelines: https://stackoverflow.com/help/how-to-ask – J. S. Jan 16 '20 at 13:25
  • 1
    @JoãoSoares I don't want any code. Just an approach or hint to how to solve the problem efficiently would do. – Samay Bhardwaj Jan 16 '20 at 13:36
  • I understand, but that's not what StackOverflow is for. Check the link I sent you above. – J. S. Jan 16 '20 at 13:48

1 Answers1

1

Hint: Usually in this kind of problems it's a good approach to check the constraints. One that gets the attention is the constraint for the variable M (up to 10). That means you can work with modular arithmetic and find the number of subset sums of size P that have a remainder 0 with M.

Adamos2468
  • 151
  • 1
  • 9