class Solution {
public:
int longestSubarray(vector<int> &nums, int limit) {
deque<int> qmax, qmin;
int l = 0, res = 0;
for (int i = 0; i < nums.size(); i++) {
int t = nums[i];
while (!qmin.empty() && qmin.back() > t)qmin.pop_back();
while (!qmax.empty() && qmax.back() < t)qmax.pop_back();
qmin.push_back(t), qmax.push_back(t);
while (!qmin.empty() && !qmax.empty() && qmax.front() - qmin.front() > limit) {
if (qmin.front() == nums[l])qmin.pop_front();
if (qmax.front() == nums[l])qmax.pop_front();
l++;
}
res = max(res, i - l + 1);
}
return res;
}
};
class Solution {
public:
int longestOnes(vector<int> &A, int K) {
int l = 0, r = 0, res = 0, n = A.size();
int cnt = 0;
while (r < n) {
if (!A[r])cnt++;
while (cnt > K) {
if (!A[l])cnt--;
l++;
}
res = max(res, r - l + 1);
r++;
}
return res;
}
};
网友评论