Data Structures & AlgorithmsModerate

Among all non-empty contiguous subarrays of 2 -1 4 -3 5 1, what is the largest sum that does NOT exceed 6?

  1. A. 6
  2. B. 8
  3. C. 1
  4. D. 12

Correct answer: A. 6

Keep prefix sums sorted and, for each P_j, binary-search the smallest earlier prefix ≥ P_j − 6. Sums of exactly 6 exist: [−1, 4, −3, 5, 1], [4, −3, 5] and [5, 1]. Unconstrained Kadane gives 8 (the whole array), and 12 adds all the positives.

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

Exams that ask this topic