ProgrammingVery hardCAT · MBA placement

For the array a = [2, 9, 4, 7, 5, 6, 3] (indices 0 to 6), the procedure below computes the sum of the maximum values of all contiguous windows of length 3, and then prints the total. What is printed?

For the array a = [2, 9, 4, 7, 5, 6, 3] (indices 0 to 6), the procedure below computes the sum of the maximum values of all contiguous windows of length 3, and then prints the total. What is printed?
total = 0
for i = 0 to n - 3
    total = total + max(a[i], a[i+1], a[i+2])
end for
Print total
  1. A. 18
  2. B. 32
  3. C. 38
  4. D. 44

Correct answer: C. 38

The window maxima are 9, 9, 7, 7, 6 for the windows starting at indices 0 to 4, totalling 38. Using the minimum of each window gives 18, windows of length 4 give 32, and running one window too far gives 44.

More Pseudocode and Code Tracing questions

Exams that ask this topic