Data Structures & AlgorithmsVery hardTCS NQT · Infosys pattern
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 return?
- A. 25
- B. 16
- C. 9
- D. 34
Correct answer: A. 25
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 25, from index 1 to 8. 16 is the sum of the whole array (wrong when some prefix should be dropped), and 9 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
- 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…
- 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 [1, 2, 0, 0, 2, 1, 0, 2, 0] (values 0, 1, 2 only)…
- 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 Boyer–Moore majority vote algorithm (candidate/counter, no verification pass) runs on [3, 4, 4, 4, 4, 1, 3, 4, 4]. What candidate and…
- A recursive function is defined as f(0) = f(1) = 1 and f(n) = f(n−1) + 2·f(n−2) for n ≥ 2. Using memoization, what is f(9)?