Suppose we have a list of numbers called nums and another value k, we have to find the length of longest sublist where the absolute difference between the largest and smallest element is ≤ k.
So, if the input is like nums = [2, 4, 6, 10] k = 4, then the output will be 3, as we can select pick [2, 4, 6] here the absolute difference is 4.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from collections import deque, defaultdict class Solution: def solve(self, A, limit): maxd = deque() mind = deque() i = 0 res = 1 for j, a in enumerate(A): while maxd and a > maxd[-1]: maxd.pop() while mind and a < mind[-1]: mind.pop() maxd.append(a) mind.append(a) while maxd[0] - mind[0] > limit: if maxd[0] == A[i]: maxd.popleft() if mind[0] == A[i]: mind.popleft() i += 1 res = max(res, j - i + 1) return res ob = Solution() nums = [2, 4, 6, 10] k = 4 print(ob.solve(nums, k))
[2, 4, 6, 10], 4
3