Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to 1.
There are two subarrays meeting the criterion: [1, 1, 2, 2] and [4, 4, 5, 5, 5]. The maximum length subarray has 5 elements.
Complete the pickingNumbers function in the editor below.
pickingNumbers has the following parameter(s):
The first line contains a single integer n, the size of the array a .
The second line contains n space-separated integers, each an a[i].
def pickingNumbers(a):
# Write your code here
answer = 0
a = sorted(a)
# [1, 3, 3, 4, 5, 6]
for i in range(len(a)-1): # fix one element
arr = [a[i]] # to save subarray
for j in range(i+1, len(a)):
if a[j] - a[i] <= 1: # defference is less than or equal to 1
arr.append(a[j])
answer = max(answer, len(arr))
# print(arr)
arr = [] # initialize arr
return answer