0

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?

  • 3
    What language do you need? Where is your attempt? What errors are you getting when you try to code this up? Please provide more detail. – artemis Apr 12 '19 at 16:11
  • `I am trying for a C++ Solution.` Don't. Write test cases / examples first. Then figure it out with pen and paper. Then finally write code. – MFisherKDX Apr 12 '19 at 16:18
  • @JerryM. I need C++. –  Apr 12 '19 at 16:18
  • `But I'm not getting the idea how to proceed`. Start with one value in the array and figure out how to solve the problem with pen and paper. Then with two values. Then finally see if you can come up with a general statement. Make sure you test combinations of values that contain common factors with M. – MFisherKDX Apr 12 '19 at 16:20
  • Last hint: pick an `a` and `M` and write down `a*k % M` for each value k=0,1,2,... until the cycle repeats. Now do this for a different value of `a`. See if you can figure out what to do. – MFisherKDX Apr 12 '19 at 16:27
  • @MFisherKDX I will try out your hint –  Apr 12 '19 at 16:30
  • @MFisherKDX Is my attempt feasible? –  Apr 12 '19 at 16:36
  • @MFisherKDX I tried it. So I calculate the max value of **a * k % M** for all the elements and store it in a new array. Then I apply the code snippet I have attempted in description on this new array. Will it give the right answer? –  Apr 12 '19 at 16:45
  • @MFisherKDX Are you trying to state a GCD approach? Please tell me if I am on the right track. –  Apr 12 '19 at 17:02
  • Not exactly, but close. Try a=2,b=4 M=10. Good luck. – MFisherKDX Apr 12 '19 at 17:14
  • @MFisherKDX Is the ans =M - gcd(a, b, c,..., M) ? Please clarify –  Apr 13 '19 at 04:35
  • @MFisherKDX Could you atleast tell me if my previous comment has the right answer? This problem is worrying me for days. I request you to provide a solution. –  Apr 13 '19 at 17:56

0 Answers0