Given an input stream of n integers, find the kth largest element for each element in the stream. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Wednesday, 1 July 2020

Given an input stream of n integers, find the kth largest element for each element in the stream.

Given an input stream of n integers, find the kth largest element for each element in the stream.

Given an input stream of n integers, find the kth largest element for each element in the stream.

Example:

Input:

2

4 6

1 2 3 4 5 6

1 2

3 4


Output:

-1 -1 -1 1 2 3

3 4 

For each test case, in a new line, print the space-separated values denoting the kth largest element at each insertion, if the kth largest element at a particular insertion in the stream doesn't exist print -1.


#include <bits/stdc++.h>

using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, m, x;
        cin >> m >> n;
        int i = m - 1;
        while (i--) {
            cout << -1 << " ";
        }

        priority_queue < int, vector < int > , greater < int > > q;

        for (i = 1; i <= n; ++i) {
            cin >> x;

            if (i > m) {
                if (q.top() >= x) {
                    cout << q.top() << " ";
                } else {

                    cout << q.top() << " ";
                    q.pop();
                    q.push(x);
                }
            } else {
                q.push(x);
            }

        }

        cout << q.top() << endl;


    }
    return 0;
}