Continuous Subarrays - Two Monotonic Queues [JS]
Description Solution: Two Monotonic Queues Use two deques to keep track of the indices of the maximum and minimum numbers so far. queueDec: monotonic decreasing queue of numbers so far queueInc: monotonic increasing queue of numbers so far For each nums[i] , count the number of subarrays that end with nums[i] . Pop out elements from the back of the queues to maintain the monotonic decreasing and increasing properties. Pop out elements from the front of the queue that have gone out of range (difference between nums[queue.front()] and nums[i] is greater than 2 ). Between the two indexes at the front of the both queues, we take the maximum index. The number of subarrays ending at nums[i] = i - Math.max(decIndex, incIndex) + 1 Time Complexity: O(n) Space Complexity: O(n) var continuousSubarrays = function(nums) { let n = nums.length, queueDec = new Deque(), queueInc = new Deque(); let ans = 0 , decIndex = 0 , incIndex =...