Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern
Kadane's algorithm runs on the array [2, -8, 4, -2, 4, -5, -2] to find the maximum sum of a contiguous subarray. What sum does it return?
- A. 4
- B. 11
- C. 6
- D. -7
Correct answer: C. 6
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 6, from index 2 to 4. -7 is the sum of the whole array (wrong when some prefix should be dropped), and 4 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 postfix (Reverse Polish) form of the infix expression "j + e f -(b + a)", built with the standard stack-based conversion (^…
- What is the sum of the minimum element over every contiguous subarray of [8, 1, 5, 4, 4, 2]?
- Binary search for first/last occurrence runs on the sorted array [5, 6, 7, 7, 15, 18, 19, 20] for target 7. What (first index, last index)…
- Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the…
- A singly linked list holds 36 -> 38 -> 51 -> 57 -> 28 -> None (in that order, 5 nodes). Using the standard two-pointer technique (advance…
- Evaluate the postfix expression: 4 3 7 + 1 -