Example: I have the array[9,0,1,2,3,6,4,5,0,9,7,8,9] and It should return the max consecutive subsequence, so the answer should be (and if the number is 9 and the next one is 0 than it's fine) 9,0,1,2,3, but my code is returning 0,1,2,3
CodePudding user response:
We can use the fact that the difference has to be either 9 or 1:
arr = np.array([9,0,1,2,3,6,4,5,0,9,7,8,9])
out = max(np.split(arr, np.where(~np.isin(np.diff(arr),[-9,1]))[0] 1), key=len)
Output:
array([9, 0, 1, 2, 3])
CodePudding user response:
Starting from each element, do a loop that compares adjacent elements, until you get a pair that isn't consecutive.
Instead of saving all the consecutive sublists in another list, just save the sublist in a variable. When you get another sublist, check if it's longer and replace it.
def constructPrintLIS(arr: list, n: int):
longest_seq = []
for i in range(n-1):
for j in range(i, n-1):
if not (arr[j] == arr[j 1]-1 or (arr[j] == 9 and arr[j 1] == 0)):
break
else:
# if we reach the end, need to update j
j = n
if j - i > len(longest_seq):
longest_seq = arr[i:j 1]
if n - i <= len(longest_seq):
# there can't be any longer sequences, so stop
break
printLIS(longest_seq)