#C14699. Maximum Length Subarray with Given Sum
Maximum Length Subarray with Given Sum
Maximum Length Subarray with Given Sum
Given an integer array \(arr\) and an integer \(k\), your task is to find the maximum length of a contiguous subarray that sums exactly to \(k\). If such a subarray does not exist, output \(0\). Note that the array can contain both positive and negative numbers.
Input: The first line contains an integer \(n\) denoting the number of elements in the array. The second line contains \(n\) space-separated integers representing the array elements. The third line contains the integer \(k\).
Output: Print the maximum length of a contiguous subarray whose sum equals \(k\). If no such subarray exists, print \(0\).
Example: For \(n = 5, arr = [1, -1, 5, -2, 3]\) and \(k = 3\), the answer is \(4\) because the subarray \([1, -1, 5, -2]\) sums up to \(3\) and has the maximum length.
inputFormat
Input is read from standard input (stdin) in the following format:
- The first line contains a single integer \(n\) (the size of the array).
- The second line contains \(n\) space-separated integers representing the elements of the array \(arr\).
- The third line contains a single integer \(k\), the target sum.
outputFormat
Output a single integer to standard output (stdout): the maximum length of a contiguous subarray whose sum equals \(k\). If no such subarray exists, output \(0\).
## sample5
1 -1 5 -2 3
3
4