Hard Cash - CASH CodeChef Easy Question

Hello Everyone , today we will be discussing a CodeChef Easy Question , HARD CASH

Its a pretty easy question , you just need to find the number of coins R that will be left over , after making the number of coins in each bag divisible by k .

So the prerequisites of solving this problem are :-
1. vectors/arrays
2. simple logic

So lets look at the solution of the problem .
So let the sum of the coins in each bag be s .
If in the end , each bag contains number of coins that are divisible by k .
So , in the end the sum of coins in all bags is also divisible by k .
So we find the smallest value r which when subtracted from s , we get a number which is divisible by k .
So the minimum value of r is the value we get above ,
Now we prove that this is indeed the answer to the question .

So , we take the coins in ith bag and put all the coins in the last bag and finally we take out the r coins from the nth bag and here we have the trivial and easiest solution .

Please take a look at the C++ code for better understanding :-

#include <iostream>
using namespace std;

int main() {
// your code goes here
int t=0;
scanf("%d",&t);
while(t--)
{
    long long n=0,k=0;
    scanf("%d",&n);
    scanf("%d",&k);
    int arr[n];
    long long i=0,sum=0;
    while(i!=n)
    {
        scanf("%d",&arr[i]);
        sum=sum+arr[i];
        i++;
    }
    cout<<sum%k<<endl;
}
return 0;
}


Please leave your doubts in the comment section 

Comments

Popular Posts