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);- A. 15
- B. 7
- C. 3
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (two-pointer: remove all occurrences of a value in place) cpp vector<int> a = {3, 2, 2, 3, 4, 3, 5}; int w = 0; for (int…
- What is printed? (stack: check if a sequence of pops is possible after pushing 1..n in order) python def valid(pushed, popped): st, j =…
- What is printed? (next greater element to the right, −1 if none) python a = [4, 5, 2, 25, 7, 8] res, st = [-1] len(a), [] for i in…
- Hash map counting: what is printed? (first element that repeats, scanning left to right) python def firstrepeat(a): seen = set() for x in…
- What is printed? (anagram check two ways) python from collections import Counter x, y = "listen", "enlists" print(sorted(x) == sorted(y)…
- Binary search: how many iterations does this loop run to find x = 23? python a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] lo, hi, it = 0…