Problem 206
Longest Subarray with Sum K
Medium · 20 pts · Array, Hash Table, Prefix Sum
Problem
You are given an array of N integers and a target K. Find the length of the longest block of consecutive elements whose sum is exactly K, or print 0 if no such block exists. Elements can be negative, so a sliding window does not work. Use prefix sums with a hash map that stores the first index at which each prefix sum occurs. At position j, if prefix[j] - K was seen first at index i, then the block after i up to j sums to K, with length j - i. Keeping only the first occurrence maximises the length.
Input
First line: integers N and K. Second line: N space-separated integers.
Output
Print the maximum length, or 0.
Constraints
1 <= N <= 100000; -10000 <= A[i] <= 10000; -1000000000 <= K <= 1000000000
Example input
5 3 1 -1 5 -2 3
Example output
4
Explanation
In 1 -1 5 -2 3 with K = 3, the first four elements give 1 - 1 + 5 - 2 = 3, a block of length 4. The whole array sums to 6, so 4 is the longest.