Longest flat stretch
def solution(A: list[int]) -> intA road survey records the elevation every 10 meters in array A. A flat stretch is a run of consecutive equal readings. Return the length of the longest flat stretch, or 0 if A is empty.
Examples
- Input
A = [3, 3, 5, 5, 5, -2, -2]
- Output
3
- Input
A = [7]
- Output
1
- Input
A = []
- Output
0
Constraints
- N is an integer within [0..100,000].
- Each element is an integer within [-1,000,000,000..1,000,000,000].
Show approach and solution
Approach
Walk the array once, keeping the length of the current run and the best run so far. The current run grows when a value equals the one before it and resets to 1 otherwise. Handle the empty array before the loop.
def solution(A):
if not A:
return 0
best = current = 1
for i in range(1, len(A)):
current = current + 1 if A[i] == A[i - 1] else 1
best = max(best, current)
return bestComplexity: O(N) time, O(1) extra space.
What the hidden tests check: An empty array, one element, all elements equal (the answer is N), the longest run at the very end, negative values, and N = 100,000.
