0

This is a hakerrank question Given a set of arrays of size and an integer , you have to find the maximum integer for each and every contiguous subarray of size for each of the given arrays.

Input Format

First line of input will contain the number of test cases T. For each test case, you will be given the size of array N and the size of subarray to be used K. This will be followed by the elements of the array Ai.

Output Format

For each of the contiguous subarrays of size of each array, you have to print the maximum integer.

Sample Input

2
5 2
3 4 6 3 4
7 4
3 4 5 8 1 4 10
Sample Output

4 6 6 4
8 8 8 10
Explanation

For the first case, the contiguous subarrays of size 2 are {3,4},{4,6},{6,3} and {3,4}. The 4 maximum elements of subarray of size 2 are: 4 6 6 4.

For the second case,the contiguous subarrays of size 4 are {3,4,5,8},{4,5,8,1},{5,8,1,4} and {8,1,4,10}. The 4 maximum element of subarray of size 4 are: 8 8 8 10.

Brute force method works fine. But it needs optimized code. I read many methods to implement. The algorithm given on geeksforgeeks works on test cases, but I am unable to comprehend the logic. One algorithm I understood and implemented as follows. But, this doesn't work on real test cases. Althouhg giving correct results on custom input and sample input. Can anyone correct me or explain any other algorithm for this problem? Please help.

#include <iostream>
#include <deque> 
using namespace std;

void printKMax(int arr[], int n, int k){
    deque<int> dq;
    //For each subarray
    //Index of max element stored at the end of deque
    for(int i=0; i<n-k+1; i++){
        //This will run only once
       if(dq.empty()){
           dq.push_back(0);
           for(int j=1; j<=k-1; j++){
               if(arr[j] > arr[i]){
                    dq.push_back(j);
               }else{
                   dq.push_front(j);
               }
           }
           cout<<arr[dq.back()]<<" ";
       }
       else{
           //Check if max index is still under current window
           if(dq.back() < i){
               dq.pop_back();
               int maxIndex=i+k-1;
               for(int j=0; j<dq.size(); j++){
                   if(arr[dq[j]] > arr[maxIndex]){
                       int temp= maxIndex;
                       maxIndex = dq[j];
                       dq[j] = temp;
                   }
               }
               dq.push_back(maxIndex);
               
           cout<<arr[dq.back()]<<" ";
           }
           else{
               //Check if new index is larger than the max of current window
               dq.pop_front();
                if(arr[dq.back()] > arr[i+k-1])
                    dq.push_front(i+k-1);
                else {
                    dq.push_back(i+k-1);
                }
                
           cout<<arr[dq.back()]<<" ";
           }
       }
    }
    cout<<"\n";
}

int main(){
  
    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
Vibhav
  • 125
  • 7
  • 5
    Your code is invalid, [C++ doesn't have variable-length arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). Please don't use so-called "competition" or "judge" sites to learn anything but bad habits, bad and in this case even invalid code. Such sites are not teaching or learning resource and shouldn't be used as such. – Some programmer dude Aug 11 '22 at 10:44
  • 1
    `int arr[n];` is not standard C++. Its odd to avoid `std::vector` but use other std containers. – 463035818_is_not_an_ai Aug 11 '22 at 10:44
  • what is a "real test case" ? What is input, output and expected output? – 463035818_is_not_an_ai Aug 11 '22 at 10:45
  • 1
    The problem with Coding Puzzles is that you learn puzzling and not coding. This is not at all the way a professional developer gets an assignment. So if you want to become a developer, you are learning the wrong things... – BoP Aug 11 '22 at 11:38
  • I think the amount of time spent here trying to make the OP feel like they are doing something wrong just for wanting to solve a problem on HackerRank is totally inappropriate. Whether you like it or not, there are many developers who find that using such sites help them get a job. In addition, they might be doing it for fun, which is also valid. – Brian Bi Aug 11 '22 at 19:11
  • Feel sorry if I wasted anyone's time. This is not about learning C++, for that any standard textbook will do. This is for learning to solve problems within given constraints. Of course there could be other methods, this problems requires using deque. The real test case is too large, it is very difficult to run and find where exectly my output differs. Always open for suggestions and criticisms. Thanks. – Vibhav Aug 12 '22 at 11:08
  • Right from the start, the logic in `if(dq.empty()){` is wrong. Given a sub-array `[1, 3, 2]`, the first value printed would be 2, not 3. The loop compares `arr[1]` and `arr[2]` to `arr[0]`, but never to each other. – Igor Tandetnik Aug 20 '22 at 21:05
  • Anyway, your algorithm is no better than brute force on the worst case, that of the array sorted in descending order. In this case, the largest element is going out of the window on every step, and you have to re-scan the new window; for overall `O(n*k)` time. – Igor Tandetnik Aug 20 '22 at 21:12

1 Answers1

0
#include <iostream>
#include <deque> 
using namespace std;

void printKMax(int arr[], int n, int k)
{
    //Write your code here.
    /* Deque-STL in C++ - Hacker Rank Solution START */
    deque<int> Qi(k);
    int i;
    for (i = 0; i < k; i++) 
    {
        while ((!Qi.empty()) && (arr[i] >= arr[Qi.back()]))
            Qi.pop_back();
        Qi.push_back(i);
    }
    for ( ; i < n; i++) {
        cout << arr[Qi.front()] << " ";
        while ((!Qi.empty()) && (Qi.front() <= i - k))
            Qi.pop_front();
        while ((!Qi.empty()) && (arr[i] >= arr[Qi.back()]))
            Qi.pop_back();
        Qi.push_back(i);
    }
    cout << arr[Qi.front()] << endl;
    /* Deque-STL in C++ - Hacker Rank Solution END */
}

int main()
{
  
    int t;
    cin >> t;
    while(t>0) 
    {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
}
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 15 '23 at 10:54