Data Structures & AlgorithmsVery hard
For the sum-at-most-K problem on a prefix-sum array with negative values, why does a balanced search structure appear in the solution?
- A. The structure stores the sum of all elements to keep the total under K.
- B. It sorts the array so that Kadane's algorithm works.
- C. For each prefix P_j, the best earlier prefix is the smallest one at least P_j − K, which needs an ordered set with binary search.
- D. It removes negative numbers before the search begins.
Correct answer: C. For each prefix P_j, the best earlier prefix is the smallest one at least P_j − K, which needs an ordered set with binary search.
Max subarray sum ≤ K equals max over j of P_j − P_i with P_i ≥ P_j − K, so the query 'smallest prefix at least a bound' is answered by an ordered set in O(log n).
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
- The shunting-yard algorithm converts the infix expression "a+bc^d^e-f^(gh)" to postfix, with ^ highest precedence and right-associative…
- What is the largest rectangular area in a histogram with bar heights 6, 2, 5, 4, 5, 1, 6 (each bar has width 1)?
- In the undirected graph with edges (1,2), (1,3), (2,4), (3,4), (4,5), (3,6), how many vertices are at shortest-path distance exactly 2…
- What is the minimum number of knight moves needed to go from square (0, 0) to (3, 3) on an 8 by 8 board (coordinates 0 to 7)?
- Two sorted linked lists are [1, 5, 9, 12] and [2, 3, 8]. They are merged into one sorted list. What is the 5th value of the merged list…
- In the array [2, 8, 5, 5, 3, 7, 5], how many index pairs i < j have a[i] + a[j] = 10?