deque problem hacker rank

Solutions on MaxInterview for deque problem hacker rank by the best coders in the world

showing results for - "deque problem hacker rank"
Christian
24 Oct 2016
1#include <iostream>
2#include <deque> 
3using namespace std;
4
5void printKMax(int arr[], int n, int k){
6	//Write your code here.
7    deque<int> dq;
8    
9    for (int i=0; i<n; i++){
10        
11        // base case for first element
12        if (dq.empty()){
13            dq.push_back(i);
14        }
15        
16        // remove elements outside the current window
17        if (dq.front() <= (i - k)){
18            dq.pop_front();
19        }
20        
21        // move max element to the front
22        while (!dq.empty() && arr[i] >= arr[dq.back()]){
23            dq.pop_back();
24        }
25        
26        dq.push_back(i);
27        
28        // print out only when the first window is completed
29        if (i >= (k - 1)){
30            cout << arr[dq.front()] << " ";
31        }    
32    }
33    cout << endl;
34}
35
36int main(){
37  
38	int t;
39	cin >> t;
40	while(t>0) {
41		int n,k;
42    	cin >> n >> k;
43    	int i;
44    	int arr[n];
45    	for(i=0;i<n;i++)
46      		cin >> arr[i];
47    	printKMax(arr, n, k);
48    	t--;
49  	}
50  	return 0;
51}
similar questions
queries leading to this page
deque problem hacker rank