1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
https://leetcode.com/problems/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 continuous subarray such that the absolute difference between any two elements is less than or equal to limit
.
In case there is no subarray satisfying the given condition return 0.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
0 <= limit <= 10^9
给定数组返回最长的满足其中最大和最小元素之间绝对差不超过limit的子数组长度。argmax + 子数组 => 动态窗口/DP。遍历,以当前元素i作为子数组底时,如果根据限制缩短窗口则该缩短将继续对i之后的元素生效,满足动态窗口条件。找sliding window max/min => 单调栈。维持两个单调栈mxq和miq分别记录sliding window内最大和最小。每次把i入栈后检查窗口的max diff,也就是mxq - miq,是否大于limit,大于说明窗口需要缩短,右移左边界l。也可以维持window size不缩小,每次大于limit时只右移l。
Last updated
Was this helpful?