Longest Equal Run
Medium · rating 1200 · Arrays
The first line contains n. The second line contains n integers. Print the length of the longest run of consecutive equal values.
Constraints: 1 ≤ n ≤ 105
Editorial
Approach
Sweep once, tracking the length of the current run. When an element equals its predecessor, extend the run; otherwise reset it to 1. Keep the maximum run length seen.
best = cur = 1
for i in range(1, n):
cur = cur + 1 if a[i] == a[i-1] else 1
best = max(best, cur)
print(best)Complexity
Time: O(n). Space: O(1).
Related problems
- Count Distinct (Sorted) — Medium
- Missing Number — Medium
- Most Frequent Element — Medium
- Second Largest — Medium
- Heaviest Row — Medium
- Kth Largest Element — Medium