TGViewer
C/C++ | LeetCode C/C++ | LeetCode @easy_c_plus_task · 3.23K subscribers
Post #1843 288
Задача: 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
Сложность: medium

Дан массив целых чисел nums и целое число limit. Вернуть размер самой длинной непустой подстроки, такая что абсолютная разница между любыми двумя элементами этой подстроки меньше или равна limit.

Пример:
Input: nums = [8,2,4,7], limit = 4
Output: 2
Explanation: All subarrays are:
[8] with maximum absolute diff |8-8| = 0 <= 4.
[8,2] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.
[2] with maximum absolute diff |2-2| = 0 <= 4.
[2,4] with maximum absolute diff |2-4| = 2 <= 4.
[2,4,7] with maximum absolute diff |2-7| = 5 > 4.
[4] with maximum absolute diff |4-4| = 0 <= 4.
[4,7] with maximum absolute diff |4-7| = 3 <= 4.
[7] with maximum absolute diff |7-7| = 0 <= 4.
Therefore, the size of the longest subarray is 2.


👨‍💻 Алгоритм:

1⃣Инициализировать два дека (minDeque и maxDeque) для хранения минимальных и максимальных значений в текущем окне и переменную left для начала окна.

2⃣Итеративно добавлять элементы в дек, поддерживая условие абсолютной разницы между максимальным и минимальным элементом в окне, чтобы она была не больше limit, при необходимости сдвигая left.

3⃣Обновлять maxLength, проверяя максимальную длину текущего окна, и возвращать maxLength как результат.

😎 Решение:
#include <queue>
#include <vector>

class Solution {
public:
int longestSubarray(std::vector<int>& nums, int limit) {
std::priority_queue<std::pair<int, int>> maxHeap;
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> minHeap;
int left = 0, maxLength = 0;

for (int right = 0; right < nums.size(); ++right) {
maxHeap.push({nums[right], right});
minHeap.push({nums[right], right});

while (maxHeap.top().first - minHeap.top().first > limit) {
left = std::min(maxHeap.top().second, minHeap.top().second) + 1;
while (maxHeap.top().second < left) {
maxHeap.pop();
}
while (minHeap.top().second < left) {
minHeap.pop();
}
}

maxLength = std::max(maxLength, right - left + 1);
}

return maxLength;
}
};


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_c_plus_task
  1. Oct 17, 2026Задача: 1137. N-th Tribonacci Number Сложность: easy Трибоначчи последовательность Tn опре…
  2. Oct 17, 2026Задача: 834. Sum of Distances in Tree Сложность: hard Есть неориентированное связное дерев…
  3. Oct 13, 2026Задача: 647. Palindromic Substrings Сложность: medium Если задана строка s, верните количе…
  4. Oct 11, 2026Задача: 37. Sudoku Solver Сложность: hard Напишите программу, которая решает судоку, запол…
  5. Oct 9, 2026Задача: 33. Search in Rotated Sorted Array Сложность: medium Дан массив nums, отсортирован…
  6. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для C/C++ разработчика, которые нигде больше не пу…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →