ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[3] = {5, -3, 5}
Integer total = 0, curMax = 0, bestMax = a[0], curMin = 0, bestMin = a[0]
for (each i from 0 to 2)
    total = total + a[i]
    curMax = max(curMax + a[i], a[i]);  bestMax = max(bestMax, curMax)
    curMin = min(curMin + a[i], a[i]);  bestMin = min(bestMin, curMin)
end for
Print bestMax, max(bestMax, total - bestMin)
  1. A. 7 7
  2. B. 10 7
  3. C. 7 10
  4. D. 5 10

Correct answer: C. 7 10

In a line, the best subarray is the whole array: 5 − 3 + 5 = 7. If the array is circular, a subarray can wrap round, and the best is total − (most negative subarray) = 7 − (−3) = 10, i.e. 5 + 5 across the wrap. Output 7 10.

More Pseudocode and Code Tracing questions

Exams that ask this topic