ProgrammingVery hardCAT · MBA placement
For the array a = [2, 9, 4, 7, 5, 6, 3] (indices 0 to 6), the procedure below computes the sum of the maximum values of all contiguous windows of length 3, and then prints the total. What is printed?
For the array a = [2, 9, 4, 7, 5, 6, 3] (indices 0 to 6), the procedure below computes the sum of the maximum values of all contiguous windows of length 3, and then prints the total. What is printed?
total = 0
for i = 0 to n - 3
total = total + max(a[i], a[i+1], a[i+2])
end for
Print total- A. 18
- B. 32
- C. 38
- D. 44
Correct answer: C. 38
The window maxima are 9, 9, 7, 7, 6 for the windows starting at indices 0 to 4, totalling 38. Using the minimum of each window gives 18, windows of length 4 give 32, and running one window too far gives 44.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [3, 1, 4, 1, 5, 9, 2, 6] is scanned from left to right. The procedure below counts the positions i (from 2 to n) where a[i] is…
- Array a = [5, 3, 8, 1] (length 4). The procedure below counts how many elements are leaders, where an element is a leader if it is…
- For the array a = [1, 2, 3, 5, 4] the next permutation (in lexicographic order) is computed by the standard procedure: find the last i…
- Array a = [3, 6, -2, -5, 7, 3]. The procedure below finds the largest product of two adjacent elements. What is printed? best = a[0] a[1]…
- The loop below prints the running count for i = 1, 4, 7, 10, ... up to and including 20 (i increases by 3 each time). What is the number…
- Array a = [1, 2, 1, 2, 3, 2, 1, 1] is processed left to right. The procedure below finds the length of the longest run of equal…