Saturday, January 24, 2015

Minimum Difference pairs


You are in the data analysis business. One of your clients needs some analysis done on her company's stock values. She has set of values which represent the change in the stock values in a single day trade over a period time. A positive value represents that the stock value was higher when the market closed compared to when the market opened on the particular day. A negative value represents fall in the stock value on the particular day. A zero implies the stock price was unchanged.

For a given set of such values, she wants to figure out what is the minimum difference between any two values in that set and the count all the pairs whose difference is equal to the minimum difference.

You will given the count of values n ( 1 <= n <= 105 ), followed by n integers Si ( -106 <= Si <= 106 ). You are expected to output the minimum difference d and the number of pairs p, where the difference is d.

Examples:
Inputs:
i)8
3 4 5 6 8 9 3 2

ii) 7
2 4 5 6 9 17 99

Outputs:
i) The minimum difference is 0, and there is only one pair of 3,3; the output will be:
0 1

ii) The minimum difference is 1, and there are two such pairs 4,5 and 5,6; the output will be:
1 2

C++ code:

#include <iostream>
#include <algorithm>
#include <cstdlib>

#define MAX_SIZE 100000

using namespace std;

// for using qsort()
int compareFunc (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

// counting sort
void rangeSort(int input[], int n){
 short CountArr[2*MAX_RANGE] = { 0 };

 for (int i=0;i<n;i++) {
  CountArr[MAX_RANGE + input[i]]++;
 }
 int outputindex=0;

 for (int j=0;j<2*MAX_RANGE;j++) {
  while (CountArr[j]--)
   input[outputindex++] = j-MAX_RANGE;
 }
}


static void FindMinimumDifference(int input[], int n, int &minDifference, int &pairCount)
{
    minDifference = -1;
    pairCount = 0;
    // Your code goes here
    //qsort (input, n, sizeof(int), compareFunc);
    rangeSort(input, n);

    int min1 = 0;
    minDifference = abs(input[1]-input[0]);
    for(int i=2;i<n;i++)
    {
     min1 = abs(input[i]-input[i-1]);
     if(min1 < minDifference){
      minDifference = min1;
      pairCount = 1;
     }
     else if(min1 == minDifference){
      pairCount++;
     }
    }
}

int main()
{
    int n;
    int input[MAX_SIZE];
    int minDifference;
    int pairCount;

    cin >> n;
    for(int i=0; i<n; i++)
    {
        cin >> input[i];
    }
    FindMinimumDifference(input, n, minDifference, pairCount);
    cout << minDifference << " " << pairCount << endl;

    return 0;
}

No comments :

Post a Comment