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?

  1. A. The structure stores the sum of all elements to keep the total under K.
  2. B. It sorts the array so that Kadane's algorithm works.
  3. 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.
  4. 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).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic