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?
- A. Two pointers: extend the right end and shrink the left end while the window sum exceeds K
- B. Sorting the array first, then taking the largest K elements
- C. Prefix sums with a hashmap of exact values, because positive sums must repeat
- 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.
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
- How many contiguous subarrays of [3, 1, 4, 1, 5, 9] have a prime sum?
- What is the minimum number of elements to delete from [4, 7, 2, 9, 5] so that the remaining sum is divisible by 3? (The empty remainder is…
- How many index pairs i < j of [1, 2, 4, 6, 7, 9] have a sum strictly between 5 and 10?
- How many index pairs i < j in [2, 5, 3, 4, 1] satisfy a[i] < a[j] and every element strictly between i and j is at most a[j]?
- What is the smallest integer k such that 3k is at least every element of [5, 10, 14, 17]?
- What is the length of the longest contiguous substring of "bbacbbcab" containing at most one letter 'a'?