# Program to find length of longest sublist with given condition in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a list of numbers called nums, we have to find the length of the longest sublist where 2 * minimum of sublist > maximum of sublist.

So, if the input is like nums = [10, 2, 6, 6, 4, 4], then the output will be 4, as the sublist [6, 6, 4,4] is the longest sublist that holds the criteria as 2 * 4 > 6.

To solve this, we will follow these steps−

• ret := 0

• define two double ended queues minq and maxq

• l := 0, r := 0

• while r < size of nums, do

• n := nums[r]

• while minq and n < nums[last element of minq], do

• delete last element from minq

• insert r at the end of minq

• while maxq and n > nums[last element of maxq], do

• delete last element from maxq

• insert r at the end of maxq

• r := r + 1

• while l < r and nums[minq] * 2 <= nums[maxq], do

• if minq is same as l, then

• delete first element of minq

• if maxq is same as l, then

• delete first element of maxq

• l := l + 1

• ret := maximum of ret and (r - l)

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, nums):
from collections import deque
ret = 0
minq, maxq = deque(), deque()
l, r = 0, 0
while r < len(nums):
n = nums[r]
while minq and n < nums[minq[-1]]:
minq.pop()
minq.append(r)
while maxq and n > nums[maxq[-1]]:
maxq.pop()
maxq.append(r)
r += 1
while l < r and nums[minq] * 2 <= nums[maxq]:
if minq == l:
minq.popleft()
if maxq == l:
maxq.popleft()
l += 1
ret = max(ret, r - l)
return ret
ob = Solution()
nums = [10, 2, 6, 6, 4, 4]
print(ob.solve(nums))

## Input

[10, 2, 6, 6, 4, 4]

## Output

4