ProgrammingHardTCS NQT · Accenture
Array a = [-2, 1, -3, 4, -1, 2, 1, -5, 4]. Kadane's algorithm below finds the maximum sum of a non-empty contiguous subarray. What is printed?
Array a = [-2, 1, -3, 4, -1, 2, 1, -5, 4]. Kadane's algorithm below finds the maximum sum of a non-empty contiguous subarray. What is printed?
cur = a[0]; best = a[0]
for i = 1 to n - 1
cur = max(a[i], cur + a[i])
best = max(best, cur)
end for
Print best- A. 6
- B. 4
- C. 1
- D. 2
Correct answer: A. 6
Kadane restarts the running sum whenever it goes negative, and the best run is 4, -1, 2, 1, which sums to 6. The largest single element gives 4, the total sum gives 1, and a running sum that never restarts gives 2.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [3, 4, 1, 2, 4, 2, 1, 3] and target K = 7. The procedure below counts contiguous subarrays whose sum is exactly K, using prefix…
- Insertion sort on the array [5, 2, 4, 6, 1, 3] shifts an element one place right each time it moves past a larger element. The procedure…
- Array a = [3, 8, 7, 2, 7]. A linear scan returns the 0-based index of the first occurrence of 7. What is printed? for i = 0 to n - 1 if…
- Binary search for the value 13 in the sorted array [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] uses lo = 0, hi = n - 1 and mid = (lo + hi) div 2…
- Array a = [8, 4, 2, 1, 7, 5]. The number of inversions (pairs i < j with a[i] > a[j]) is the number of out-of-order pairs, and merge sort…
- Prefix sums are computed for a = [4, 1, 7, 3, 2, 8] with P[0] = 0 and P[k] = a[1] + ... + a[k]. A range sum for 1-based positions l to r…