Track the length of the constant suffix of the scanned prefix:
best = 0; run = 0
for i = 0,...,n-1:
    if i == 0 or a[i] != a[i-1]: run = 1
    else: run = run+1
    if run > best: best = run
return best
The condition is evaluated with short-circuit logic, so a[-1] is never accessed. After processing index , run is the longest constant segment of an array ending there and best is the longest anywhere in . A maximal constant segment either extends the preceding suffix or starts at a changed value, proving the update. Empty input returns zero. Time is , with constant auxiliary storage.

Articles by others on the same topic (0)

There are currently no matching articles.