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.

Example 1:

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.

Example 2:

Input: nums = [10,1,2,4,7,2], limit = 5
Output: 4 
Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.

思路:求任意两个值的相差绝对值<limit,也就是最大值和最小值的相差< limit,维护区间最大和最小,那么就是deque,滑动窗口了,注意这题写j move,shrink i,比较好写; array里面存的是index;O(N).

class Solution {
    public int longestSubarray(int[] nums, int limit) {
        Deque<Integer> maxDeque = new LinkedList<>();
        Deque<Integer> minDeque = new LinkedList<>();
        
        int res = 0;
        int i = 0;
        for(int j = 0; j < nums.length; j++) {
            // move j;
            while(!maxDeque.isEmpty() && nums[maxDeque.peekLast()] < nums[j]) {
                maxDeque.pollLast();
            }
            maxDeque.addLast(j);
            
            while(!minDeque.isEmpty() && nums[j] < nums[minDeque.peekLast()]) {
                minDeque.pollLast();
            }
            minDeque.addLast(j);
            
            // move i;
            while(nums[maxDeque.peekFirst()] - nums[minDeque.peekFirst()] > limit) {
                if(nums[maxDeque.peekFirst()] == nums[i]) {
                    maxDeque.pollFirst();
                }
                if(nums[minDeque.peekFirst()] == nums[i]) {
                    minDeque.pollFirst();
                }
                i++; // shrink i;
            }
            
            // update res;
            res = Math.max(res, j - i + 1);
        }
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值