Sunday, June 20, 2010

Maximum Positive Difference[Amazon]

Amazon Question
There is an integer array consisting positive and negative integers. Find maximum positive difference S defined as:

S = a [i.]- a[j] where i>j
and
S > 0

7 comments:

  1. take the first element of the array as the minimum and subtract it from every number greater than it .
    and save the greatest of them.
    as soon as you find any number smaller than it then consider it as minimum and do the same for it.

    Now compare the results.
    The Largest one will be the answer.

    ReplyDelete
  2. Here is the code in C:


    #include
    #include
    #include

    void main()
    {

    //diff variables and arrays required in the code a,i,j & k are counters

    int a,arr[7],i,j,k,diff[7],S,min,max;

    clrscr();
    a=0;

    //To take input array from user
    printf("enter the numbers");
    for(i=0;i<7;i++)
    {
    scanf("%d",&arr);
    }

    j=0;
    //Loop to get the different differences of the minimum values from there preceding //values

    while(j<7)
    {
    min=arr[j];
    max=arr[j+1];
    i=j+1;

    // To find the maximum number from the values following the minimum value
    while(arr>=min)
    {
    if(arr[i+1]>max)
    {
    max = arr[j+1];
    a++;
    }
    diff[a] = max-min;
    i++;
    }
    To increment j directly to the position containing smaller value
    j = j+i;
    }

    //To find the maximum of all the differences
    S=diff[0];
    for(i=1;i<=a;i++)
    {
    if (diff[a]>S)
    S = diff[a];
    }
    printf("here is the answer %d",S);
    getch();
    }

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. simple sort the array and take difference between the last and the first element

    ReplyDelete
  5. my problem is
    i want to find min diff in any two no. in array and array size is 10 so plz give solution.

    ReplyDelete
  6. @Rohit : Please read the question correctly..
    You ucan't sort the array coz you can only subtract a no fron the nos. on right hand side of it. :)

    ReplyDelete
  7. @ the problem posted above i.e. to find the minimum difference :
    Sort the Array and subtract every no. from the next no. in the list .
    This way you can easily find the minimum difference.

    ReplyDelete