We are given two Arrays A and B of size n with containing only positive integers. we are allowed to modify elements of array A such that A[i]=A[i]*B[j] or A[i]=A[i]+B[j], where 0<=i,j<n. we are allowed to use each element of array B only once. Find the maximum product of Array A after at most n operation. The purpose of question is to look for correct and better algorithms.
example:
A={2,3,5};
B={1,6,4};
output= 1080
Explanation:
A[0]=2+1=3
A[1]=3*4=12
A[2]=5*6=30
product=30*12*3=1080
My approach:
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int testcases; cin>>testcases;
for(int i=0;i<testcases;i++){
int n;cin>>n;
vector<int>a(n);
vector<int>b(n);
for(int j=0;j<n;j++){
cin>>a[j];
}
for(int j=0;j<n;j++){
cin>>b[j];
}
sort(a.begin(),a.end());
sort(b.begin(),b.end());
for(int j=0;j<n;j++){
a[j]=max(a[j]+b[j],a[j]*b[j]);
}
int answer=a[0];
for(int j=1;j<n;j++){
answer=answer*a[j];
}
cout<<answer<<endl;
}
}
But, it passed only 1 testcases, and was getting wrong answer for others. kindly looking for help to approach this question.
Example of failing test cases;
A = [1,2]
B = [1,2]
My answer = 8
Correct answer = 9= [(1+2) * (1+2)]