ProgrammingHardInfosys · Cognizant

Array a = [1, 2, 1, 2, 3, 2, 1, 1] is processed left to right. The procedure below finds the length of the longest run of equal consecutive values. What is printed?

Array a = [1, 2, 1, 2, 3, 2, 1, 1] is processed left to right. The procedure below finds the length of the longest run of equal consecutive values. What is printed?
best = 1; run = 1
for i = 1 to n - 1
    if a[i] == a[i-1] then run = run + 1 else run = 1
    best = max(best, run)
end for
Print best
  1. A. 2
  2. B. 7
  3. C. 3
  4. D. 1

Correct answer: A. 2

The only repeated pair is 1 1 at the end, so the longest run is 2. Counting changes instead of equal neighbours gives 7 or a different run length, counting distinct values gives 3, and starting the run at 0 gives 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic