Sunday, October 20, 2013

[Amazon interview] Minimum absolute difference between two arrays

Given two sorted arrays of equal length, how do u find a pair of numbers one from each array such that absolute difference between two numbers is minimum.

1 comment:

  1. #include
    #include
    #include
    void findMaxDiff(int a[], int b[], int size1, int size2)
    {
    int i=0, j=0, pos1=0, pos2=0;
    int minDiff=INT_MAX;
    while(i<size1 && j<size2)
    {
    if(abs(a[i]-b[j])<minDiff)
    {
    minDiff=abs(a[i]-b[j]);
    pos1=i;
    pos2=j;
    }
    if(a[i]<=b[j])
    {
    i++;
    }
    else
    {
    j++;
    }
    }
    printf(" Minimum difference between %d and %d is %d\n", a[pos1], b[pos2],minDiff);
    }
    int main()
    {
    int a[] = {5, 9, 12, 15, 18, 25};
    int b[] = {1, 3, 6, 10, 17, 22};
    int size1=sizeof(a)/sizeof(a[0]);
    int size2=sizeof(b)/sizeof(b[0]);
    findMaxDiff(a,b,size1, size2);
    getch();
    return 0;
    }

    ReplyDelete