Simple linear algorithm (Python, I'm sure the code can be improved):
# Your array arr = [ (100, 10), (110, 2), (112, 5), (117, 3), (300, 5), (305, 5), (400, 5), (405, 10), (415, 2), (417, 4), (421, 7), (428, 1), (429, 6), (500, 4), (504, 9) ] # Where does each element end? ends = map(sum, arr) s, e = 0, 0 # start and end of longest contiguous subseq cur = 0 # length of current contiguous subseq for j, i in enumerate(range(1, len(arr))): # See if current element is contiguous with the previous one if (arr[i][0] == ends[j]): cur += 1 elif cur > 0: # If not, we may have found the end of a (currently) longest subseq if cur > (e - s): e = j s = e - cur cur = 0 # reset subseq length # The longest contiguous subseq may be at the end of the array if cur > (e - s): e = j + 1 s = e - cur # print the start and end index of the longest contiguous subseq print(s, e)
source share