Program to find the size of the longest sublist where car speed is constant in python


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 −

  • j := 1
  • max_cnt := 0, current := 0
  • distance := |positions[0] - positions[1]|
  • while j < size of positions, do
    • prev := positions[j - 1]
    • if distance is same as |positions[j] - prev| , then
      • current := current + 1
    • otherwise,
      • max_cnt := maximum of max_cnt and current
      • current := 1
      • distance := |positions[j] - prev|
    • max_cnt := maximum of max_cnt and current
    • j := j + 1
  • return max_cnt + 1

Let us see the following implementation to get better understanding −

Example 

Live Demo

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))

Input

[0, 4, 8, 12, 6, 4, 0]

Output

4

Updated on: 02-Dec-2020

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements