ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (maximum sum of any 4 consecutive elements, sliding window)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (maximum sum of any 4 consecutive elements, sliding window)? (Arrays are indexed from 0.)
Integer arr[9] = {1, 4, 2, 10, 2, 3, 1, 0, 20}
Integer k = 4
Integer cur = arr[0] + arr[1] + arr[2] + arr[3]
Integer best = cur
for (each i from k to 8)
    cur = cur + arr[i] - arr[i - k]
    best = max(best, cur)
end for
Print best
  1. A. 17
  2. B. 24
  3. C. 26
  4. D. 20

Correct answer: B. 24

Sliding a window of size 4 across the array gives sums 17,18,17,16,6,24 for the 6 possible windows. The window starting at index 5, {3,1,0,20}, gives 24, the overall maximum.

More Pseudocode and Code Tracing questions

Exams that ask this topic