Advertisement
exmkg

Untitled

Sep 28th, 2024
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. class Solution {
  2.     public int longestSubarray(int[] nums, int limit) {
  3.         Deque<Integer> maxDeque = new LinkedList<>();
  4.         Deque<Integer> minDeque = new LinkedList<>();
  5.  
  6.         int left = 0;
  7.         int maxLength = 0;
  8.  
  9.         for (int right = 0; right < nums.length; ++right) {
  10.             // Maintain the maxDeque in decreasing order
  11.             // Maintain the minDeque in increasing order
  12.             while (!maxDeque.isEmpty() && maxDeque.peekLast() < nums[right]) maxDeque.pollLast();
  13.             while (!minDeque.isEmpty() && minDeque.peekLast() > nums[right]) minDeque.pollLast();
  14.  
  15.             maxDeque.offerLast(nums[right]);
  16.             minDeque.offerLast(nums[right]);
  17.  
  18.             // Check if the current window exceeds the limit
  19.             while (maxDeque.peekFirst() - minDeque.peekFirst() > limit) {
  20.                 // Remove the elements that are out of the current window
  21.                 if (maxDeque.peekFirst() == nums[left]) maxDeque.pollFirst();
  22.                 if (minDeque.peekFirst() == nums[left]) minDeque.pollFirst();
  23.                 ++left;
  24.             }
  25.  
  26.             maxLength = Math.max(maxLength, right - left + 1);
  27.         }
  28.         return maxLength;
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement