Skip to content
Advertisement

Count total subsequences whose sum is divisible by k

I am trying to write a DP solution for the problem: count total number of sub-sequences possible of an array whose elements’ sum is divisible by k.

I have written the following solution. But it is not giving the correct result. Like in the following code snippet, the array is {1, 2, 1} and k = 3. So expected total number of sub sequences divisible by 3 is 2, but the actual result is 3 which is clearly incorrect.

Please point out my mistake.

JavaScript

Advertisement

Answer

Let s denote a sequence of length N, and K be a given divisor.

dp[i][j] = the number of subsequences of s[0..i] with remainder equal to j. We will compute dp for all 0 <= i < N and 0 <= j < K.

JavaScript

The result is dp[N - 1][0]

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement