I am trying to solve the problem 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit. I got the logic but there was a very weird problem due to which I had to pull my hair for more than two hours.
Here is the code :-
class Solution {
public int longestSubarray(int[] nums, int limit) {
Deque<Integer> maxDeque = new LinkedList();
Deque<Integer> minDeque = new LinkedList();
Queue<Integer> queue = new LinkedList();
int maxLength = 1;
for (int i = 0; i < nums.length; i++) {
Integer temp = nums[i];
//int temp = nums[i]; //If I uncomment this line and comment the above line, the code does not work.
queue.offer(temp);
while (!maxDeque.isEmpty() && maxDeque.peekLast() < temp) {
maxDeque.removeLast();
}
while (!minDeque.isEmpty() && minDeque.peekLast() > temp) {
minDeque.removeLast();
}
maxDeque.offerLast(temp);
minDeque.offerLast(temp);
while (maxDeque.peekFirst() - minDeque.peekFirst() > limit) {
if (queue.peek() == maxDeque.peekFirst()) {
maxDeque.pollFirst();
}
if (queue.peek() == minDeque.peekFirst()) {
minDeque.pollFirst();
}
queue.poll();
}
maxLength = Math.max(maxLength, queue.size());
}
return maxLength;
}
}
You see when I put an integer into each of the queues, the code runs fine but when I put an int into the three queues, I get a TLE. So, in the below code, if temp is Integer
, the code passes but when temp is int
, it gives a TLE. Can someone please explain what is going on ?