Question:
Minimums in Array: Geeksforgeeks
From the given two arrays of equal size, find the sum of two numbers one from each array such that the sum is minimum and the corresponding indices are not the same. Else print -1.
Input:
3
3
1 2 3
1 2 3
3
1 2 3
1 5 10
4
5 64 86 4
7 87 6 4
Output:
3
3
9
Explanation:
Testcase 1:
Here the minimum sum is (1+2) 3 or (2+1) .
Not 2(1+1) because of same indicesa 0 ,0.
Testcase 2:
Here the minimum is 3 (2+1)
Test case 3:
Here the minimum is 9 (5+4).
Code:
#include<stdio.h>
int func()
{
int n;
scanf("%d",&n);
int a[n];// first array
int b[n];//second array
int i;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
if(n==1)
{
printf("-1\n");
return 0;
//since both the indices are the same
}
//find least two in both the arrays
int a1=0;
for(i=0;i<n;i++)
{
if(a[i]<a[a1])
{
a1=i;
}
}
// now find a2 from left and right of a1
//lefft of a1
int a2;
if(a1+1<=n-1)
{
a2=a1+1;
}
else
{
a2=a1-1;
}
for(i=0;i<a1;i++)
{
if(a[i]<a[a2])
{
a2=i;
}
}
for(i=a1+1;i<n;i++)
{
if(a[i]<a[a2])
{
a2=i;
}
}
// now for second array
int b1=0;
for(i=0;i<n;i++)
{
if(b[i]<b[b1])
{
b1=i;
}
}
// now find a2 from left and right of a1
//lefft of a1
int b2;
if(b1+1<=n-1)
{
b2=b1+1;
}
else
{
b2=b1-1;
}
for(i=0;i<b1;i++)
{
if(b[i]<b[b2])
{
b2=i;
}
}
for(i=b1+1;i<n;i++)
{
if(b[i]<b[b2])
{
b2=i;
}
}
//printf("%d %d %d %d\n",a1,a2,b1,b2);
if(a1!=b1)
{
printf("%d\n",a[a1]+b[b1]);
}
else
{
if( (a[a1]+b[b2]) <= (a[a2]+b[b1]) )
{
printf("%d\n",a[a1]+b[b2]);
}
else
{
printf("%d\n",a[a2]+b[b1]);
}
}
return 0;
}
int main()
{
int cases,i;
scanf("%d",&cases);
for(i=0;i<cases;i++)
{
func();
}
return 0;
}

No comments:
Post a Comment