ProgrammingHardInfosys · Cognizant

Array a = [1, 3, 2, 3, 4, 1] is searched for the longest strictly increasing contiguous run. The procedure below returns its length. What is printed?

Array a = [1, 3, 2, 3, 4, 1] is searched for the longest strictly increasing contiguous run. The procedure below returns its length. 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. 3
  2. B. 5
  3. C. 6
  4. D. 2

Correct answer: A. 3

The runs are 1-3 (length 2), 2-3-4 (length 3) and then 1, so the longest is 3. Counting the adjacent pairs gives 5, treating any change as a rise gives 6, and starting the run at 0 gives 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic