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)- A. 7 7
- B. 10 7
- C. 7 10
- 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.
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? Integer n = 5, spaces = 0, stars = 0 for (each i from 1 to n) for (each j from 1 to n…
- What will be the output of the following pseudocode? (~ is bitwise NOT, & is AND, | is OR, >> is right shift) Integer x = 11 Integer a =…
- What will be the output of the following pseudocode? (^ is XOR, & is AND) Integer a = 10, b = 20, x, flips = 0 x = a ^ b while (x > 0) x =…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Function f(Integer n) if (n <=…
- What will be the output of the following pseudocode? Integer calls = 0 Procedure f(Integer n) calls = calls + 1 for (each i from 1 to n…
- What will be the output of the following pseudocode? Integer t[0..10] t[0] = 0 t[1] = 1 t[2] = 1 for (each i from 3 to 10) t[i] = t[i - 1]…