Monday, 8 September 2014

You have an array of n elements and a sum. check if 2 elements in the array sum to given sum. Complexity : O(n)

#include <stdio.h>
#include <stdlib.h>
int memory[2000],a[20],sum,n,i,f;
int main()
{
   printf("Enter the number of elements:");
   scanf("%d",&n);

   printf("Enter %d elements:",n);
   for(i=0;i<n;i++)
    scanf("%d",&a[i]);

   printf("Enter the sum of two elements:");
   scanf("%d",&sum);

   for(i=0;i<n;i++)
    if(sum>a[i])
      memory[sum-a[i]]=1;

   for(i=0;i<n;i++)
   if(memory[a[i]]==1){
    f=1;
    printf("Req. elements : %d %d \n",sum-a[i],a[i]);
   }
     if(f==0)
        printf("No such elements exist\n");

    return 0;
}

No comments:

Post a Comment