Program to find length of longest sublist where difference between min and max smaller than k in Python

PythonServer Side ProgrammingProgramming

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 −

  • Create two double ended queue maxd, mind
  • i := 0, res := 1
  • for each index j and value a in A, do
    • while maxd is not 0 and a > last element of maxd, do
      • delete last element from maxd
    • while mind is not 0 and a < last element of mind, do
      • delete last element from mind
    • insert a at the end of maxd
    • insert a at the end of mind
    • while maxd[0] - mind[0] > limit, do
      • if maxd[0] is same as A[i], then
        • delete item from left of maxd
      • if mind[0] is same as A[i], then
        • delete item from left of mind
      • i := i + 1
    • res := maximum of res and (j - i + 1)
  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

[2, 4, 6, 10], 4

Output

3
raja
Published on 19-Nov-2020 11:54:10
Advertisements