Given array of positive integer, find the largest number c such that c=a+b

#include <stdio.h>
#include <stdlib.h>


/* Comparator function */
int intCompare(int *a, int *b)
{
return *a - *b;
}

int maxsum(int a[], int n)
{
/* Sort the array */
qsort(a, n, sizeof(int), intCompare);

int i, j;

while(n--)
{
i = 0;
j = n - 1;

/* Check whether 0 <= i <= n-1, 0 <= j <= n-1 exists such that a[i] + a[j] = a[n] */

while(i < j)
{
int sum = a[i] + a[j];

if(sum == a[n])
return sum;

if(sum > a[n])
j--;
else
i++;
}
}

/* Can't find any such num */
return -1;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s