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

void printKMax(int arr[], int n, int k) {
    deque<int>dq;
    int i;
    for (i = 0; i < k; i++) {
        while (dq.back() < arr[i]) {
            dq.pop_back();
            dq.push_back(i);
        }
    }
    for (; i < n; i++) {
        cout << dq.front();
        while (dq.front() <= i - k) {
            dq.pop_front();
        }
        while (dq.back() < arr[i]) {
            dq.pop_back();
            dq.push_back(i);
        }
    }
    cout << dq.front();
}

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;
}

I don't know where I did wrong in program that caused the following errors appear:

  • This error appears when program run to this code in arr[n]

expression must have a constant value the value of variable cannot be used as a constant

expression did not evaluate to a constant

If someone knows how to solve above errors, please help me.

Thanks you so much.

1 Answers1

0

I don't know where I did wrong in program that caused the following errors appear: This error appears when program run to this code in arr[n]

The C++ standard doesn't require that a conforming compiler supports Variable Length Arrays.

Dynamic stack allocations may be supported by the implementation anyway. Many compilers support alloca/_alloca to do a stack allocation that will be automatically freed at the end of the function.

The general advice is to not use these. The stack should not be the target of a user-selectable amount of data.

In C++, there's a simple stand-in solution. Allocate the memory dynamically (on the heap, if there is one):

#include <vector>

//...

std::vector<int> arr(n);

From a user's perspective, this is an almost perfect stand-in for int arr[n];

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108