Suppose we have a list of numbers representing the position of a car at equally spaced intervals of time. We have to find the size of the longest sublist where the car was traveling at a constant speed.
So, if the input is like positions = [0, 4, 8, 12, 6, 4, 0], then the output will be 4, as the sublist is [0, 4, 8, 12].
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, positions): j = 1 max_cnt = 0 current = 0 distance = abs(positions[0] - positions[1]) while j < len(positions): prev = positions[j - 1] if distance == abs(positions[j] - prev): current += 1 else: max_cnt = max(max_cnt, current) current = 1 distance = abs(positions[j] - prev) max_cnt = max(max_cnt, current) j += 1 return max_cnt + 1 ob = Solution() positions = [0, 4, 8, 12, 6, 4, 0] print(ob.solve(positions))
[0, 4, 8, 12, 6, 4, 0]
4