#K85967. Longest Contiguous Subarray with Given Sum
Longest Contiguous Subarray with Given Sum
Longest Contiguous Subarray with Given Sum
You are given an unsorted array nums
of n integers and an integer target
. Your task is to find the length of the longest contiguous subarray whose sum is equal to target
. If no such subarray exists, output 0.
The problem can be formally defined as: Find the maximum length L such that for some indices l and r with 0 ≤ l ≤ r < n
, the following holds:
This is a classic problem that can be efficiently solved using prefix sums and a hash map.
inputFormat
The first line of the input contains two space-separated integers: n
(the size of the array) and target
.
The second line contains n
space-separated integers representing the array nums
.
outputFormat
Output a single integer which is the length of the longest contiguous subarray whose sum is equal to target
. If no such subarray exists, output 0.
5 3
1 -1 5 -2 3
4
</p>