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
ANSWER: SOLUTION IN JAVA.
import java.util.*;
public class codevita {
public static void main(String []args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),i,j,k,r,min=0,min1=0,sum,sum1;
System.out.print("\t");
k=sc.nextInt();
System.out.println();
int []a=new int[n];
int []b=new int[n];
for( i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println();
for( i=0;i<n;i++)
b[i]=sc.nextInt();
for(i=0;i<n;i++){
sum=0;
a[i]-=2*k;
for(j=0;j<n;j++){
sum+=a[j]*b[j];
}
if(i==0)
min=sum;
a[i]+=2*k;
if(min>=sum){
min=sum;
}
}
for(i=0;i<n;i++){
sum1=0;
a[i]+=2*k;
for(j=0;j<n;j++){
sum1+=a[j]*b[j];
}
if(i==0)
min1=sum1;
a[i]-=2*k;
if(min1>=sum1){
min1=sum1;
}
}
if(min<min1)
System.out.println(min);
else System.out.println(min1);
sc.close();
}
}
INPUT:
3 4
3 4 5
5 6 7
OUTPUT: 18
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 whitespace
- 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
Output the minimum sum of products of the two arrays
Constraints:
- 1 ≤ N ≤ 10^5
- 0 ≤ |A[i]|, |B[i]| ≤ 10^5
- 0 ≤ K ≤ 10^9
ANSWER: SOLUTION IN JAVA.
import java.util.*;
public class codevita {
public static void main(String []args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),i,j,k,r,min=0,min1=0,sum,sum1;
System.out.print("\t");
k=sc.nextInt();
System.out.println();
int []a=new int[n];
int []b=new int[n];
for( i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println();
for( i=0;i<n;i++)
b[i]=sc.nextInt();
for(i=0;i<n;i++){
sum=0;
a[i]-=2*k;
for(j=0;j<n;j++){
sum+=a[j]*b[j];
}
if(i==0)
min=sum;
a[i]+=2*k;
if(min>=sum){
min=sum;
}
}
for(i=0;i<n;i++){
sum1=0;
a[i]+=2*k;
for(j=0;j<n;j++){
sum1+=a[j]*b[j];
}
if(i==0)
min1=sum1;
a[i]-=2*k;
if(min1>=sum1){
min1=sum1;
}
}
if(min<min1)
System.out.println(min);
else System.out.println(min1);
sc.close();
}
}
INPUT:
3 4
3 4 5
5 6 7
OUTPUT: 18
running efficiently and giving minimum sum by modification.
ReplyDelete