ProgrammingHardTCS NQT · Accenture

Array a = [5, 1, 4, 2, 3, 7]. The procedure below counts the interior local maxima, that is, positions i from 1 to n - 2 whose value is strictly greater than both neighbours. What is printed?

Array a = [5, 1, 4, 2, 3, 7]. The procedure below counts the interior local maxima, that is, positions i from 1 to n - 2 whose value is strictly greater than both neighbours. What is printed?
count = 0
for i = 1 to n - 2
    if a[i] > a[i-1] and a[i] > a[i+1] then count = count + 1
end for
Print count
  1. A. 3
  2. B. 1
  3. C. 2
  4. D. 6

Correct answer: B. 1

Only 4 is greater than both neighbours (1 and 2) among the interior positions, so the count is 1. Counting elements greater than the left neighbour gives 3, counting interior local minima gives 2, and the array length is 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic