ProgrammingHardTCS NQT · Accenture pattern
What will be the output of the following pseudocode (Kadane's maximum subarray sum)? (Arrays are indexed from 0.)
What will be the output of the following pseudocode (Kadane's maximum subarray sum)? (Arrays are indexed from 0.)
Integer arr[9] = {-2, 1, -3, 4, -1, 2, 1, -5, 4}
Integer maxEnd = arr[0], maxSoFar = arr[0]
for (each i from 1 to length(arr) - 1)
maxEnd = max(arr[i], maxEnd + arr[i])
maxSoFar = max(maxSoFar, maxEnd)
end for
Print maxSoFar- A. 6
- B. 7
- C. 4
- D. 10
Correct answer: A. 6
This is Kadane's algorithm. The best contiguous subarray here is {4, -1, 2, 1}, summing to 6, which the running maxEnd/maxSoFar tracking correctly identifies as the overall maximum.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What is the time complexity of binary search on a sorted array of n elements? Function binarySearch(Array arr, Integer target) Integer lo…
- What is the worst-case time complexity of the following pseudocode (bubble sort) on an array of n elements? for (each i from 0 to n - 2)…
- What is the time complexity of the following recursive pseudocode (computing n choose k via Pascal's identity), in the worst case, as a…
- What is the space complexity (auxiliary stack space) of the following recursive factorial function for input n? Function fact(Integer n)…
- What will be the output of the following pseudocode (anagram check via sorting)? Function isAnagram(String a, String b) return…
- What will be the output of the following pseudocode (duplicate detection using a set)? Function hasDuplicate(Array arr) Set seen = empty…