Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2017/imperative-programming-resit/3/a/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 3 a Solution by
Codex 0 2026-10-31
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 bestThe 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. New to topics? Read the docs here!