Minimum Product Array
TCS codevita 2016 round 1:
The task is to find the minimum sum of Products of two arrays of the same size, given that k modifications are allowed on the first array. In each modification, one array element of the first array can either be increased or decreased by 2.Note- the product sum is Summation (A[i]*B[i]) for all i from 1 to n where n is the size of both arrays.
Input Format:
First line of the input contains n and k delimited by white space Second line contains the Array A (modifiable array) with its values delimited by spaces Third line contains the Array B (non-modifiable array) with its values delimited by spaces.
Output Format:
Output the minimum sum of products of the two arrays.
Constraints:
1 ≤ N ≤ 10^50 ≤ |A[i]|, |B[i]| ≤ 10^50 ≤ K ≤ 10^9
Sample Input Output
1. 3 5 -31
1 2 -3
-2 3 -5
2. 5 3 25
2 3 4 5 4
3 4 2 3 2
Explanation for sample 1:
Here total numbers are 3 and total modifications allowed are 5. So we modified A[2], which is -3 and increased it by 10 (as 5 modifications are allowed). Now final sum will be
(1 * -2) + (2 * 3) + (7 * -5)
-2 + 6 - 35
-31
-31 is our final answer.
Explanation for sample 2:
Here total numbers are 5 and total modifications allowed are 3. So we modified A[1], which is 3 and decreased it by 6 (as 3 modifications are allowed).
Now final sum will be
(2 * 3) + (-3 * 4) + (4 * 2) + (5 * 3) + (4 * 2)
6 - 12 + 8 + 15 + 8
25
25 is our final answer.
PROGRAM:
#include<stdio.h>
int main()
{
int m[10],i,min,max,k,n,p=1,sum=0,u[10],mins;
scanf("%d",&n);
scanf("%d",&k);
for(i=0;i<n;i++)
scanf("%d",&u[i]);
for(i=0;i<n;i++)
scanf("%d",&m[i]);
min=m[0];
max=m[0];
for(i=0;i<n;i++)
{
if(m[i]<min)
min=m[i];
if(m[i]>max)
max=m[i];
}
if (min<0&&max<0)
mins=min<max?min:max;
else if(min>0&&max>0)
mins=max>min?max:min;
else
{
if((min-max)<-(2*min))
mins=min;
else
mins=max;
}
for(i=0;i<n;i++)
{
if(mins==m[i]&&mins>0)
{
u[i]=u[i]-(2*k);
goto x;
}
if(mins==m[i]&&mins<0)
{
u[i]=u[i]+(2*k);
goto x;
}
}
x:for(i=0;i<n;i++)
{
p=u[i]*m[i];
sum=sum+p;
}
printf("%d",sum);
return 0;
}
OUTPUT:
5 3
2 3 4 5 4
3 4 2 3 2
25
You can directly run it on a IDE: https://ide.geeksforgeeks.org/lP9ISaZ9yx
You can comment your feedback and doubts if any cheers!
Related links: Zombie World
One of the test cases for this program shows that it has segmentation fault. Could you tell me how to clear that?
ReplyDeletewhich one? can you comment the test case also?
Deletetest case 2
DeleteBut, i am getting the output for both the test cases as per above code. https://ide.geeksforgeeks.org/lP9ISaZ9yx
Deletecheck out this link and execute the program in this link.