0

I am practicing some Dynamic Programming problems and encounter this problem

Given an array of n(1<=n<=1000) integers and a positive integer k(k<=1000). Find the longest subsequence whose sum is divisible by k.

For example, a = [1,6,11,5,10,15,20,2,4,9] and k=5.

The result should be: [9,4,20,15,10,5,11,6] because 9+4+20+15+10+5+11+6 = 80, which is divisible by 5.

What is a suitable approach to solve this problem?

shayanmalinda
  • 1,925
  • 3
  • 12
  • 23
  • 1
    Please read: [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Evg Jul 29 '20 at 08:07
  • So we can assume it is not contiguously embedded within the array? –  Jul 29 '20 at 08:09
  • 1
    Seems like the subset sum problem. Add up all the numbers. The total is 83. So then the question becomes, "Is there a subset that sums to 3?" In the example, the subset {1,2} exists and we're done. If no subset sums to 3, then you would need to try 8, then 13, then 18, etc. – user3386109 Jul 29 '20 at 08:14

2 Answers2

2

Start with the longest possible subsequence, the array itself. Calculate its sum modulo k. If its zero, we are done. Otherwise, find a number such that its modulo k is the same. If that exists, remove it and we are done. Otherwise keep going.

2

Brute Force Approach:

We can generate all the possible sub-sequences and then find the largest sub-sequence among them whose sum is divisible by K.

However, the time complexity of this approach will be O(n*n).

Efficient Approach:

We can use dynamic programming here. Kindly note that this approach will only work for small values of K.

dp[i][curr_mod] = max(dp[i + 1][curr_mod], dp[i + 1][(curr_mod + arr[i]) % m] + 1)

Here, dp[i][curr_mod] stores the longest subsequence of subarray arr[i…N-1] such that the sum of this subsequence and curr_mod is divisible by K.

At each step, either index i can be chosen to update curr_mod or it can be ignored.

Also, note that only SUM % m needs to be stored instead of the entire sum as this information is sufficient to complete the states of DP.

Ayush Jain
  • 181
  • 7