Given an array=[a, b, c, ...].
You have to find the maximum value of [a * k1 + b * k2 + c * k3 + ...]%M. Where k1,k2,k3.. are any desired non-negative integers you can choose. M is known.
Language- C++
Example
Input
arr=[7, 3, 2].
M=10
Output
9
Explanation
You can choose to make the array [7 * 1 + 3 * 0 + 2 * 1 ] % 10.
Here k1 = 1, k2 = 0, k3 = 1 .
So you get 9 as the answer(max value).
Edit-
I am trying for a C++ Solution.
My attempt:
I know that the ans will range from 0 to M-1. But I'm not getting the idea how to proceed.
Edit
My attempt
int ans=arr[0];
for(int i=1; i<arr.length(); i++){
ans=max((ans+arr[i])%M,ans);
}
return ans;
Here I traverse the array from left to right going on updating the ans. Is this correct?