#C11343. Longest Subarray with Given Sum

    ID: 40649 Type: Default 1000ms 256MiB

Longest Subarray with Given Sum

Longest Subarray with Given Sum

Given an array of integers and a target integer \(k\), find the length of the longest contiguous subarray whose sum is exactly \(k\). In other words, for a subarray with indices \(l\) to \(r\) (0-indexed), you need to check if

\(\sum_{i=l}^{r} a_i = k\).

If there is no such subarray, output 0. This problem requires an efficient solution, typically using prefix sums and a hash map, to achieve \(O(n)\) time complexity.

Example: For the array [1, -1, 5, -2, 3] and \(k = 3\), the longest subarray is [1, -1, 5, -2] with a length of 4.

inputFormat

The input consists of three lines:

  1. An integer \(n\) representing the number of elements in the array. Note that \(n\) can be 0.
  2. If \(n > 0\), a line containing \(n\) space-separated integers representing the elements of the array. This line will be empty if \(n = 0\).
  3. An integer \(k\) representing the target sum.

outputFormat

Output a single integer representing the length of the longest contiguous subarray that sums exactly to \(k\). If no such subarray exists, output 0.

## sample
5
1 -1 5 -2 3
3
4