#K80982. Longest Subarray with Target Sum

    ID: 35651 Type: Default 1000ms 256MiB

Longest Subarray with Target Sum

Longest Subarray with Target Sum

Given an array of integers and a target integer T, find the length of the longest contiguous subarray whose sum equals T. If no such subarray exists, output 0.

Let the array be denoted by \(a_0, a_1, \ldots, a_{n-1}\). We want to find indices \(i\) and \(j\) (with \(0 \le i \le j < n\)) such that

\(\sum_{k=i}^{j} a_k = T\)

The solution employs the prefix sum technique and a hash map (or dictionary) to efficiently determine the longest subarray meeting the condition.

inputFormat

The input is given via stdin and consists of three lines:

  1. An integer n representing the number of elements in the array.
  2. n space-separated integers which represent the array.
  3. An integer T representing the target sum.

outputFormat

Output a single integer to stdout which is the length of the longest contiguous subarray whose sum equals T. If no such subarray exists, output 0.

## sample
8
1 2 3 4 5 6 7 8
7
2