'Need help in Python hackerrank problem solving

So, I am stuck on a question and I am not sure what I am doing wrong with my code.

Question is- Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to . Example a = [1,1,2,2,4,4,5,5,5]
There are two subarrays meeting the criterion: and .
The maximum length subarray has elements.
[1,1,2,2] and [4,4,5,5,5]

Returns int: the length of the longest subarray that meets the criterion

or visit the link Hackerrank Problem

def pickingNumbers(a):
    a.sort()
    answer = 0
    flag = False
    for i in range(len(a)-1,1,-1):
        count = 0
        temp = [list(l) for l in list(itertools.combinations(a,i))]
        for j in temp:
            for k in range(len(j)-1):
                if abs( j[k+1] - j[k] ) <= 1:
                    count +=1
            if count == len(j):
                answer = len(j)
                break


Solution 1:[1]

Note that the statement asks you to to find a subarray, not subsequence. A subarray is a continuous chain of elements from the parent array. Here by sorting the array you are destroying the parent array's order whenever the array given to you is ascending. Hence your program will give wrong output

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aniket Sharma