Data Structures & AlgorithmsModerateCodeforces Div2 B-D · ICPC regional

An array has only positive integers and you need the longest contiguous subarray whose sum is at most K, with n up to 10^6. Which method is correct and fast?

  1. A. Two pointers: extend the right end and shrink the left end while the window sum exceeds K
  2. B. Sorting the array first, then taking the largest K elements
  3. C. Prefix sums with a hashmap of exact values, because positive sums must repeat
  4. D. Dynamic programming over all subarray pairs, because sums are not monotone

Correct answer: A. Two pointers: extend the right end and shrink the left end while the window sum exceeds K

Positive values make the window sum non-decreasing as the right end grows, so the shrink rule is valid and the scan is linear. Sorting destroys the contiguity the problem requires.

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

Exams that ask this topic