Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a91c22a

Browse files
committed
Add solution #1438
1 parent 2a451c7 commit a91c22a

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,302 LeetCode solutions in JavaScript
1+
# 1,303 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1097,6 +1097,7 @@
10971097
1434|[Number of Ways to Wear Different Hats to Each Other](./solutions/1434-number-of-ways-to-wear-different-hats-to-each-other.js)|Hard|
10981098
1436|[Destination City](./solutions/1436-destination-city.js)|Easy|
10991099
1437|[Check If All 1's Are at Least Length K Places Away](./solutions/1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy|
1100+
1438|[Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit](./solutions/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.js)|Medium|
11001101
1443|[Minimum Time to Collect All Apples in a Tree](./solutions/1443-minimum-time-to-collect-all-apples-in-a-tree.js)|Medium|
11011102
1446|[Consecutive Characters](./solutions/1446-consecutive-characters.js)|Easy|
11021103
1447|[Simplified Fractions](./solutions/1447-simplified-fractions.js)|Medium|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
3+
* https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of integers nums and an integer limit, return the size of the longest non-empty
7+
* subarray such that the absolute difference between any two elements of this subarray is less than
8+
* or equal to limit.
9+
*/
10+
11+
/**
12+
* @param {number[]} nums
13+
* @param {number} limit
14+
* @return {number}
15+
*/
16+
var longestSubarray = function(nums, limit) {
17+
const maxDeque = [];
18+
const minDeque = [];
19+
let result = 0;
20+
let left = 0;
21+
22+
for (let right = 0; right < nums.length; right++) {
23+
while (maxDeque.length && nums[maxDeque[maxDeque.length - 1]] <= nums[right]) {
24+
maxDeque.pop();
25+
}
26+
maxDeque.push(right);
27+
28+
while (minDeque.length && nums[minDeque[minDeque.length - 1]] >= nums[right]) {
29+
minDeque.pop();
30+
}
31+
minDeque.push(right);
32+
33+
while (nums[maxDeque[0]] - nums[minDeque[0]] > limit) {
34+
if (maxDeque[0] < minDeque[0]) {
35+
left = maxDeque.shift() + 1;
36+
} else {
37+
left = minDeque.shift() + 1;
38+
}
39+
}
40+
41+
result = Math.max(result, right - left + 1);
42+
}
43+
44+
return result;
45+
};

0 commit comments

Comments
 (0)