ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (maximum sum of any window of size k)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (maximum sum of any window of size k)? (Arrays are indexed from 0.)
Integer arr[6] = {2, 1, 5, 1, 3, 2}
Integer k = 3
Integer window = arr[0] + arr[1] + arr[2]
Integer best = window
for (each i from k to length(arr) - 1)
    window = window + arr[i] - arr[i - k]
    best = max(best, window)
end for
Print best
  1. A. 9
  2. B. 8
  3. C. 7
  4. D. 10

Correct answer: A. 9

The sliding window sums are: {2,1,5}=8, {1,5,1}=7, {5,1,3}=9, {1,3,2}=6. The maximum among these is 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic