I've seen some longest consecutive sequence problems before such as find the increasing subsequence. I am now trying to further develop my skills. Given an array of integers, I want to find the longest consecutive sequence where the difference of all the elements in the respective subsequence is less than a given number, e.g. 3. An example is [10,11,12,15,13] where only the first three elements fulfill the condition. Also, I want to return the indexes of the first and last element from the given array.
I was thinking of making two functions; get_first_element(arr) and get_last_element(arr).
def get_last_ele(arr):
longest_seq = 0
last_ele = 0
max_difference = 3
for i in range (0, len(arr)):
max_ele_seq = arr[i]
min_ele_seq = arr[i]
_count = 0
_last_ele = i
for j in range(i,len(arr)-i+1):
ele_j = arr[j]
if ele_j > max_ele_seq:
max_ele_seq = ele_j
if ele_j < min_ele_seq:
min_ele_seq = ele_j
if abs(max_ele_seq - min_ele_seq) > max_difference:
break
last_ele = j
_count += 1
if _count > longest_seq:
longest_seq = _count
last_ele = last_ele
return last_ele
I feel like I can re-use this code to get the first element, but that will be redundant to have two similar functions. Is it possible to implement all of this in one function, and are there any better solutions with regards to time complexity?
for j in range(i,len(arr)-i+1):rather thanfor j in range(i,len(arr)):? - DarrylG