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- A. 17
- B. 24
- C. 26
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode (reversing an array in groups of size k)? (Arrays are indexed from 0.) Integer arr[8]…
- What will be the output of the following pseudocode? (A square matrix's main diagonal is mat[i][i]; its anti-diagonal is mat[i][n-1-i]. If…
- This function uses a counter that PERSISTS across calls (a static/global variable), starting at 3. What does each of the 7 calls print, in…
- What will be the output of the following pseudocode? Function isEven(Integer n) if (n == 0) return true end if return isOdd(n - 1) end…
- What will be the output of the following pseudocode? Integer c = 0 for (each i from 1 to 12) for (each j from i + 1 to 12) if ((i + j) mod…
- What will be the output of the following pseudocode? (& is bitwise AND, >> is right shift.) Integer n = 1958, c = 0 while (n > 0) c = c +…