#C10460. Longest Subarray with Sum K
Longest Subarray with Sum K
Longest Subarray with Sum K
Given an array of n integers and an integer k, find the length of the longest contiguous subarray whose sum is equal to k.
You are required to implement an efficient algorithm that computes this length. If no subarray sums to k, output 0.
Hint: Consider using prefix sums and a hash map (or equivalent) to store the earliest occurrence of each prefix sum. The core idea is to find indices i and j such that:
\( prefix[j] - prefix[i] = k \)
which implies that the subarray from i+1 to j sums to k. The answer is the maximum length j - i over all valid pairs.
inputFormat
The input is read from standard input (stdin) and consists of three lines:
- The first line contains an integer n, the number of elements in the array.
- The second line contains n space-separated integers representing the array.
- The third line contains an integer k, the target sum.
outputFormat
Output to standard output (stdout) a single integer representing the length of the longest contiguous subarray whose sum equals k. If such a subarray does not exist, output 0.
## sample5
1 -1 5 -2 3
3
4