ProgrammingVery hardTCS NQT · Accenture

For the array a = [-1, 4, -2, 6, -3, 5], the procedure below finds the maximum sum of a contiguous window of exactly 3 elements (windows start at index 0 to n-3). What is printed?

For the array a = [-1, 4, -2, 6, -3, 5], the procedure below finds the maximum sum of a contiguous window of exactly 3 elements (windows start at index 0 to n-3). What is printed?
best = sum of a[0..2]
for i = 1 to n - 3
    best = max(best, sum of a[i..i+2])
end for
Print best
  1. A. 1
  2. B. 4
  3. C. 9
  4. D. 8

Correct answer: D. 8

The window sums are 1, 8, 1 and 8, so the maximum is 8. Taking the minimum window gives 1, using windows of length 2 gives 10, and the total sum of the array is 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic