#K49512. Existence of Subarray With Sum k
Existence of Subarray With Sum k
Existence of Subarray With Sum k
You are given an array of integers and a target integer (K). Your task is to determine if there exists a contiguous subarray within the given array that sums exactly to (K). This problem tests your understanding of prefix sums and hash-based lookups to achieve an efficient solution.
The idea is to maintain a cumulative sum while iterating through the array and check if the difference between the current sum and (K) has been seen before. If it has, then a contiguous subarray summing to (K) exists.
Example: For instance, given the array [1, 2, 3, 7, 5] and (K = 15), the subarray [1, 2, 3, 7, 5] sums to 15.
Note: The input is read from standard input and the output should be printed to standard output.
inputFormat
The first line contains two integers (N) and (K) separated by a space, where (N) is the number of elements in the array and (K) is the target sum. The second line contains (N) space-separated integers representing the array elements.
outputFormat
Output a single line containing either "YES" if there exists a contiguous subarray whose sum is exactly (K), or "NO" otherwise.## sample
5 15
1 2 3 7 5
YES