You are given a list of numbers and a separate number x. Your task is to find the length of the longest contiguous segment of the list such that:
- the last number of the segment is greater than or equal to the first number of the segment, and
- the difference between the last and the first number of the segment is at most x.
You may assume that the length of the list is at most 10^5 and that the list numbers and x are in the range 1 \dots 10^9.
In a file segments.py
, implement a function find
that returns the length of the longest valid segment.
def find(t, x): # TODO if __name__ == "__main__": print(find([1, 4, 6], 1)) # 1 print(find([1, 4, 6], 10)) # 3 print(find([4, 1, 10, 5, 14], 1)) # 4 print(find([4, 1, 10, 5, 14], 10)) # 5 print(find([9, 8, 7, 6, 5, 4, 3, 2, 1], 100)) # 1
Explanation: In the third example, the segment [4, 1, 10 ,5] of length 4 satisfies 4 \le 5 and 5-4 \le 1, and the only segment of length 5, [4, 1, 10, 5, 14], does not satisfy the second condition since 14-4 > 1.