ProgrammingHardCapgemini · Infosys pattern
What will be the output of the following pseudocode? (Arrays are indexed from 0.)
What will be the output of the following pseudocode? (Arrays are indexed from 0.)
Integer arr[6] = {5, -2, 3, -1, 4, -6}
Integer s = 0, m = 0
for (each i from 0 to 5)
s = s + arr[i]
if (s < 0)
s = 0
end if
if (s > m)
m = s
end if
end for
Print m- A. 12
- B. 3
- C. 5
- D. 9
Correct answer: D. 9
This is Kadane's algorithm. s runs 5, 3, 6, 5, 9, 3 and never drops below 0, so it is never reset. The maximum is 9 (5 - 2 + 3 - 1 + 4). The total of all elements, 3, is the trap.
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 x = 7, y = 3 Print x mod y y + x / y
- What will be the output of the following pseudocode? (Arrays are indexed from 0.) Integer arr[6] = {1, 2, 3, 4, 5, 6} for (each i from 0…
- How many times is fun called in total when fun(6) is evaluated? Function fun(Integer n) if (n <= 2) return 1 end if return fun(n - 1) +…
- What will be the output of the following pseudocode? Integer c = 0, j for (each i from 1 to 10) j = i while (j <= 10) c = c + 1 j = j + i…
- What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right…
- What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right…