ProgrammingHardInfosys · Cognizant

The array a = [2, 3, 4, 1, 2, 3, 9] is scanned for its longest run of consecutive positions where each element is exactly one more than the previous element. The procedure below prints the length of the longest such run. What is printed?

The array a = [2, 3, 4, 1, 2, 3, 9] is scanned for its longest run of consecutive positions where each element is exactly one more than the previous element. The procedure below prints the length of the longest such run. What is printed?
best = 1; run = 1
for i = 1 to n - 1
    if a[i] == a[i-1] + 1 then run = run + 1 else run = 1
    best = max(best, run)
end for
Print best
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 1

Correct answer: B. 3

The runs 2, 3, 4 and 1, 2, 3 each have length 3, so the answer is 3. Accepting any rise gives 4 (the final 3, 9 also counts), counting distinct values gives 5, and accepting only steps of minus one gives 1 here.

More Pseudocode and Code Tracing questions

Exams that ask this topic