1

I have an array with n elements ,i need to calculate all n*n sum of pair of two elements (array[i]+array[j]).All sums are arranged in ascending order.I need to find Kth sum

for example:

array[] = {3,4,5}

all sums: {(3+3),(3+4),(4+3),(3+5),(5+3),(4+4),(4+5),(5+4),(5+5)}

K = 6

I need to find value for Kth sum ( in this case 6th sum is 4+4 ,i will return 8);

Solution might be very optimal


this is my solution; it isn't optimal:

for(i=0;i<n;i++)
    fin>>a[i];
qsort(a, n, sizeof(int), int_cmp);
for(i=0;i<n;i++)
    for(j=i;j<n;j++)
            {
                sum[k]=a[i]+a[j];
                if(i!=j)
                    sum[++k]=a[i]+a[j];
                k++;
                }
qsort(sum, n*n, sizeof(int), int_cmp);
cout<<sum[nrs-1];
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mike York
  • 11
  • 2

1 Answers1

0

I have seen a similar kind of question from google interview question in that they use two sorted array instead of one but the solution works.One optimization which will work in O(klogk) can be given here. To find the maximum value in such a case it is necessary to have calculated all the values lesser than it,ie let i,j be the maximum values in your case 5,5 to consider 5,5 to be max it is necessary to have evaluated both 4,5and 5,4.that is i-1,j and i,j-1 So a working code will be to use a heap in c++ it is a priority queue. The code is as follows

#include <iostream>  
#include <queue>  

using namespace std;   
for(i=0;i<n;i++)
fin>>a[i];
qsort(a, n, sizeof(int), int_cmp);
std::priority_queue<int > heap;


heap.add(pair(n-1, n-1));  // biggest pair n=array size

// remove max k-1 times 
for (int i = 0; i < k - 1; ++i) {
// get max and remove it from the heap
max = heap.pop();

// add next candidates
heap.push(pair(max.i - 1, max.j));
heap.push(pair(max.i, max.j - 1));
}

// get k-th maximum element
max = heap.pop();
maxVal = a[max.i] + a[max.j];

Now this one is optimized upto O(k.logk) there is another one which gives O(k).You can find it here.Kth sum in O(k)

Community
  • 1
  • 1
  • Thanks a lot for this idea .But i still have a problem .I have some errors : 1) error: no type named 'value_type' in 'struct std::greater' 2)error: template argument 3 is invalid| I think i have to add a library or something – Mike York Apr 01 '15 at 16:33
  • I have added the necessary modifications in the code. It is a thing about library or rather STL – anugrah nayar Apr 01 '15 at 23:43