- Related Questions & Answers
- Program to find size of sublist where product of minimum of A and size of A is maximized in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest sublist whose sum is 0 in Python
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find length of longest sublist with given condition in Python
- Program to find length of longest sublist where difference between min and max smaller than k in Python
- Program to find longest equivalent sublist after K increments in Python
- Program to find length of longest strictly increasing then decreasing sublist in Python
- Program to find the maximum sum of circular sublist in Python
- Program to find the sum of largest K sublist in Python
- Program to find size of smallest sublist whose sum at least target in Python
- Program to find largest average of sublist whose size at least k in Python
- Python program to Find the size of a Tuple
- Program to Find the longest subsequence where the absolute difference between every adjacent element is at most k in Python.
- Program to find a sublist where first and last values are same in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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

Advertisements