Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / Additional-2024-IS / solutions / sliding-window.maximum.cpp
blob: 242cd6aeb34ea67a6054926ced400f3bd901cf31 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <deque>
#include <vector>

std::vector<int> sliding_window_maximum(const std::vector<int> v, unsigned k)
{
    std::vector<int> result;
    std::deque<int> window;

    for (size_t i = 0; i < k; i++)
    {
        while(!window.empty() && window.back() < v[i])
        {
            window.pop_back();
        }
        window.push_back(v[i]);
    }
    
    result.push_back(window.front());

    for (size_t i = k; i < v.size(); i++)
    {
        if(window.front() == v[i-k])
            window.pop_front();
        
        while(!window.empty() && window.back() < v[i])
        {
            window.pop_back();
        }

        window.push_back(v[i]);

        result.push_back(window.front());
    }

    return result;
}

int main()
{

}