-
Notifications
You must be signed in to change notification settings - Fork 0
/
1438.绝对差不超过限制的最长连续子数组.cpp
41 lines (37 loc) · 1.06 KB
/
1438.绝对差不超过限制的最长连续子数组.cpp
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
/*
* @lc app=leetcode.cn id=1438 lang=cpp
*
* [1438] 绝对差不超过限制的最长连续子数组
*/
// @lc code=start
#include <vector>
#include <set>
class Solution {
public:
int longestSubarray(std::vector<int>& nums, int limit) {
if (nums.empty()) { return 0; }
if (nums.size() == 1) { return 1; }
int head = 0, tail = 1;
std::multiset<int> record;
record.insert(nums[head]);
record.insert(nums[tail]);
int result = 1;
while (tail < nums.size()) {
if (std::abs(*record.begin() - *record.rbegin()) > limit) {
if (auto it = record.find(nums[head]); it != record.end()) {
record.erase(it);
}
head++;
} else {
result = std::max(tail - head + 1, result);
tail++;
if (tail >= nums.size()) {
break;
}
record.insert(nums[tail]);
}
}
return result;
}
};
// @lc code=end