[LeetCode] Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int longestSubarray(vector<int>& A, int limit) {
multiset<int> ms;
int res = 0;
for(int l = 0, r = 0; r < A.size(); r++) {
ms.insert(A[r]);
while(!ms.empty() and *ms.rbegin() - *ms.begin() > limit) {
ms.erase(ms.find(A[l++]));
}
res = max(res, r - l + 1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.