Data Structures & AlgorithmsVery hardProduct-company MCQ pattern
Kadane's algorithm runs on the array [5, 4, 4, -3, -5, -1, 8] to find the maximum sum of a contiguous subarray. What sum does it return?
- A. 8
- B. 13
- C. 16
- D. 12
Correct answer: B. 13
Tracing Kadane's algorithm (reset the running sum to the current element whenever it drops to zero or below, else extend it) gives a best contiguous sum of 13, from index 0 to 2. 12 is the sum of the whole array (wrong when some prefix should be dropped), and 8 is just the single largest element, which ignores combining it with neighbours.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is the sum of the minimum element over every contiguous subarray of [9, 4, 5, 3, 1, 9, 8, 1]?
- QuickSort (last element as pivot, Lomuto-style partition) sorts [31, 34, 38, 59, 23, 16, 54, 42, 46]. Counting one comparison per element…
- Array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] is left-rotated by d = 2 positions using the reversal algorithm (reverse first d, reverse rest…
- Two sorted linked lists [9 → 14 → 35 → 36 → 37] and [27 → 29 → 31 → 32] are merged with the standard O(n+m) two-pointer merge (always take…
- Kadane's algorithm runs on the array [-9, 3, 3, -2, 6, 4, -4, 6, 9] to find the maximum sum of a contiguous subarray. What sum does it…
- Elevation map [4, 6, 0, 2, 6, 6, 6, 2] (bar width 1). Using the two-pointer / prefix-max approach for trapping rain water, how much water…