LeetCode 1438. 绝对差不超过限制的最长连续子数组

题目链接

1438. 绝对差不超过限制的最长连续子数组

注意事项

multiset中取最大值:rebegin
multiset中取最小值:begin

代码

class Solution {
public:
    int longestSubarray(vector<int>& nums, int limit) {

        int ans = 0;
        int cnt = 0;
        int start = 0;
        int end = 0;
        multiset<int> ms;

        while (end < nums.size()){
            ms.insert(nums[end]);
            cnt++;
            if (abs(*ms.rbegin() - *ms.begin()) <= limit){
                end++;
                continue;
            }
            ans = max(ans, cnt - 1);

            while (cnt > 1 && abs(*ms.rbegin() - *ms.begin()) > limit){
                ms.erase(ms.find(nums[start]));
                cnt--;
                start++;
            }
            end++;
        }

        ans = max(ans, cnt);

        return ans;
    }
};
posted @ 2022-08-26 17:39  Frodo1124  阅读(15)  评论(0编辑  收藏  举报