Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern
Kadane's algorithm runs on the array [-9, 1, 7, 5, 7, -3, 0, -7, 1] to find the maximum sum of a contiguous subarray. What sum does it return?
- A. 20
- B. 23
- C. 7
- D. 2
Correct answer: A. 20
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 20, from index 1 to 4. 2 is the sum of the whole array (wrong when some prefix should be dropped), and 7 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
- QuickSort (last element as pivot, Lomuto-style partition) sorts [57, 6, 37, 10, 15, 58]. Counting one comparison per element checked…
- Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the…
- The Dutch National Flag algorithm (single pass, three pointers low/mid/high) partitions [2, 0, 0, 1, 0, 1, 1, 0] (values 0, 1, 2 only) in…
- Array [87, 4, 31, 36, 38, 63, 75] is a sorted array rotated at pivot 6. Using the standard O(log n) rotated-array binary search (decide…
- Array [56, 73, 74, 82, 90, 3, 48] is a sorted array rotated at pivot 2. Using the standard O(log n) rotated-array binary search (decide…
- The Boyer–Moore majority vote algorithm (candidate/counter, no verification pass) runs on [1, 5, 5, 2, 5, 1, 5, 5]. What candidate and…