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- A. 1
- B. 4
- C. 9
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [4, 9, 2, 8, 2, 7]. The procedure below counts the prefix records, that is, the positions i where a[i] is strictly greater than…
- A rotated sorted array a = [4, 5, 6, 7, 0, 1, 2] has its smallest element at some index. The procedure below finds that index by a linear…
- The loops below print the pairs (i, j) with 1 <= i <= j <= 3 in order, and the procedure prints the total count of pairs. What is printed?…
- Array a = [3, 1, 2]. The procedure below performs a stable count of the number of ways the array can be read in increasing order using…
- Array a = [1, 3, 2, 3, 4, 1] is searched for the longest strictly increasing contiguous run. The procedure below returns its length. What…
- Array a = [5, 1, 4, 2, 3, 7]. The procedure below counts the interior local maxima, that is, positions i from 1 to n - 2 whose value is…