#include <iostream>
#include <vector>
#include <deque>
#include <algorithm>

using namespace std;

int longestSubarray(vector<int>& nums, int limit) {
    deque<int> max_d, min_d;
    int i = 0, res = 0;
    for (int j = 0; j < nums.size(); ++j) {
        while (!max_d.empty() && nums[j] > max_d.back()) max_d.pop_back();
        while (!min_d.empty() && nums[j] < min_d.back()) min_d.pop_back();
        max_d.push_back(nums[j]);
        min_d.push_back(nums[j]);

        while (max_d.front() - min_d.front() > limit) {
            if (max_d.front() == nums[i]) max_d.pop_front();
            if (min_d.front() == nums[i]) min_d.pop_front();
            i++;
        }
        res = max(res, j - i + 1);
    }
    return res;
}

int main() {
    vector<int> test = {4, 2, 3, 6, 2, 2, 3, 2, 7};
    int limit = 1;
    cout << "Longest N-stable: " << longestSubarray(test, limit) << endl; // Output: 4
    return 0;
}