educative.io

Can you check if my cpp implementation is correct?

I didn’t use deque but I want to know if my O(n) implementation is correct, I felt like the dataset run against my solution is weak.
vector find_max_sliding_window(vector& v, int window_size) {

 vector<int> result;

    int n = v.size() - window_size;

    int res=v[0];

    int indice=0;

    int res2=v[0];

    int indice2=0;

    for(int i=0;i<window_size;i++){

        if(v[i]>=res){

            res=v[i];

            indice=i;

        }else{

            if(res2<=v[i]){

                res2=v[i];

                indice2=i;

            }

        }

    }

    result.push_back(res);

    for (auto i=window_size; i < v.size() ; ++i)

    {

        if(indice>i-window_size){

            if(res<=v[i]){

                res=v[i];

                indice=i;

            }else{

            if(res2<=v[i]){

                res2=v[i];

                indice2=i;

            }

        }

        } else{

            if(indice2>i-window_size){

                if(res2<=v[i]){

                    res=max(v[i],res2);

                    indice=i;

                   

                }else{

                    res=res2;

                    indice=indice2;

                }

                indice2=i;

                    res2=0;

               

            }

        }  

       

        result.push_back(res);

    }

    return result;

}

Type your question above this line.

Course: https://www.educative.io/collection/5642554087309312/5679846214598656
Lesson: https://www.educative.io/collection/page/5642554087309312/5679846214598656/210002

@Omar_Sehlouli Yes, your code is running fine, but using an array would be a better option. An array is a reference object, so if you use the array [index], it will get a value without a loop from 0 to the index.

1 Like