#K51492. Smallest Subarray with Target Sum
Smallest Subarray with Target Sum
Smallest Subarray with Target Sum
Given an array of positive integers, the task is to find the length of the smallest contiguous subarray whose elements sum exactly to a given target value \(X\). If no such subarray exists, output \(-1\). The input consists of multiple test cases and for each, you are provided with the array and the target sum. Analyze the array to efficiently determine the minimum length of the subarray that satisfies the condition.
Note: Each test case gives two integers \(N\) and \(K\) on the first line, where \(N\) is the length of the array and \(K\) is the maximum value in the array (this parameter is provided for additional constraints but you may not need it directly in your algorithm). The following line contains \(N\) integers representing the array, and the last line of the test case contains the target sum \(X\).
The problem requires reading from standard input and writing to standard output. Make sure your solution handles edge cases, such as when no subarray adds up to \(X\), in which case the output should be \(-1\) for that test case.
inputFormat
The first line of input contains an integer \(T\) representing the number of test cases. Each test case is described as follows:
- The first line contains two integers \(N\) and \(K\): the length of the array and the maximum value in the array respectively.
- The second line contains \(N\) space-separated positive integers which form the array \(A\).
- The third line contains an integer \(X\) representing the target sum.
All input is read from standard input (stdin).
outputFormat
For each test case, output a single integer representing the length of the smallest contiguous subarray whose sum equals \(X\). If no such subarray exists, output \(-1\). Each result should be printed on a new line to standard output (stdout).
## sample2
5 5
1 2 3 4 5
9
6 3
1 1 1 1 1 1
4
2
4
</p>