Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

Sliding window: what is printed? (maximum sum of any 3 consecutive elements)

Sliding window: what is printed? (maximum sum of any 3 consecutive elements)
int a[] = {4, -1, 6, -2, 3, 5, -4, 2};
int n = 8, k = 3, s = 0, best;
for (int i = 0; i < k; i++) s += a[i];
best = s;
for (int i = k; i < n; i++) {
    s += a[i] - a[i - k];
    if (s > best) best = s;
}
printf("%d", best);
  1. A. 15
  2. B. 7
  3. C. 3
  4. D. 9

Correct answer: D. 9

Window sums: 9 (4−1+6), 3, 7, 6, 4, 3. The first window is already the best: 9. Initialising best after the first slide gives 7, printing s instead of best gives the last window 3, and 15 is the unrestricted maximum subarray (Kadane), which ignores k = 3.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic