It is from a programming question.
The question is as follows:
An array of numbers will be given along with the number k we have to divide with. And we have to choose elements from that array such that the sum of those element is divisible by k. The sum of those elements should be as large as possible.
Input:
On the first line n, denoting the number of elements.
On the next line n numbers are given.
On the next line k is given by which we have to divide.
Output:
Largest sum as possible by choosing elements from that array s.t. sum is divisible by k.
Sample Input:
5
1 6 2 9 5
8
Sample Output:
16
Note that 16 is obtainable by more than one combinations of numbers, but we're here concerned only about maximum sum.
My Proposed Solution:
I traverse over array and maintain cumulative sum in an array b for the given input array like:
b=[1 7 9 18 23]
and taking mod of numbers in array b by k and store it to
c=[1 7 1 2 7]
Now the numbers having the same value in c i.e. index 0 and index 2; index 1 and index 4. Now i have got all solutions, and the answer would be
max(b[2]-b[0],b[4]-b[1])
And is in a case three indexes have same value in c i.e. in case where
c=[1 2 3 1 1 2]
The answer would be
max(b[4]-b[0],b[5]-b[1])
Basically subtracting the leftmost occurrence of that number with the rightmost occurrence.
My solution only works if there are contiguos elements s.t. sum of elements is divisible by k. Expecting a description of the correct solution
1 2 3 4 5, can we choose1 2 5? - IVlad