#C5123. Longest Contiguous Subarray with Given Sum

    ID: 48738 Type: Default 1000ms 256MiB

Longest Contiguous Subarray with Given Sum

Longest Contiguous Subarray with Given Sum

Given an array of integers, your task is to find the length of the longest contiguous subarray whose elements sum to a specified target value. In other words, find indices l and r (with l ≤ r) such that (S = \sum_{i=l}^{r} a_i) equals the target and the length (r - l + 1) is maximized. If no such subarray exists, output 0.

This problem requires you to efficiently compute contiguous subarray sums and use prefix sum techniques to achieve an optimal solution.

inputFormat

The input is given via standard input (stdin) in the following format:

  • The first line contains an integer (n) representing the number of elements in the array.
  • The second line contains (n) space-separated integers representing the array (a_0, a_1, \dots, a_{n-1}).
  • The third line contains an integer representing the target sum.

Example:

5 1 2 3 4 -1 5

outputFormat

Output a single integer on standard output (stdout), which is the length of the longest contiguous subarray with a sum equal to the target. If no such subarray exists, output 0.## sample

5
1 2 3 4 -1
5
2