<p>You are given an array of integers&nbsp;<code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>

<p>Return <em>the max sliding window</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3
<strong>Output:</strong> [3,3,5,5,6,7]
<strong>Explanation:</strong> 
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       <strong>3</strong>
 1 [3  -1  -3] 5  3  6  7       <strong>3</strong>
 1  3 [-1  -3  5] 3  6  7      <strong> 5</strong>
 1  3  -1 [-3  5  3] 6  7       <strong>5</strong>
 1  3  -1  -3 [5  3  6] 7       <strong>6</strong>
 1  3  -1  -3  5 [3  6  7]      <strong>7</strong>
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> [1]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= k &lt;= nums.length</code></li>
</ul>

class Solution {
public:
    int t[400005];
    void build(vector <int>& t, vector <int>& nums, int pos, int l, int r){
        if(l == r){
            t[pos] = nums[l - 1];
            return;
        }
        int mid = (l + r) >> 1;
        build(t, nums, pos << 1, l, mid);
        build(t, nums, pos << 1 | 1, mid + 1, r);
        t[pos] = max(t[pos << 1], t[pos << 1 | 1]);
    }

    int query(vector <int>& t, int pos, int l, int r, int u, int v){
        if(l > v || r < u)
            return -1e9;
        if (u <= l && v >= r)
            return t[pos];
        int mid = (l + r) >> 1;
        int leaf1 = query(t, pos << 1, l, mid, u, v);
        int leaf2 = query(t, pos << 1 | 1, mid + 1, r, u , v);
        return max(leaf1, leaf2);
    }
    
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int n = nums.size();
        vector <int> t(4 * n, 0);
        build(t, nums, 1, 1, n);
        vector <int> res;
        for (int i = 1; i + k - 1 <= n; ++i){
            int cur = query(t, 1, 1, n, i, i + k - 1);
            res.push_back(cur);
        }
        return res;
    }
};
154958