I know this has been posted before but I tried to do on my way
I tried to code but which is showing erroneous result! obviously there is error in my logic..can anyone please explain me where am I having error?
here we are assuming that arrays are sorted in descending order!
int kthlargestsum(int a[], int b[],int k)
{
int aIndex=0;
int bIndex=0;
int sum=0;
int i;
for(i=0;i<k;++i)
{
if(a[aIndex]>b[bIndex])
{
sum+=a[aIndex];
++aIndex;
}
else
{
sum+=a[bIndex];
++bIndex;
}
}
printf("the output is %d",sum);
}
main()
{
int a[]={10,9,6,4,2};
int b[]={11,9,7,1};
int k;
printf("enter the value of k \n");
scanf("%d",&k);
kthlargestsum(a,b,k);
}
First off,
a[bIndex]seems suspect to me. Perhaps you wantb[bIndex]?For anything else, you’ll have to be more clear on what the problem you’re trying to solve actually is (examples are always nice:). What you code appears to do is to add up
kentries from the two arrays. This is now how I would interpret “Find kth largest of sum of elements in 2 array”.