#C3443. Contiguous Subarray Sum
Contiguous Subarray Sum
Contiguous Subarray Sum
You are given an array of n integers and a target value k. Your task is to determine whether there exists a contiguous subarray whose sum is equal to k.
This problem can be approached using prefix sums. Recall that the cumulative sum at index \(i\) is defined as \(S_i = a_1 + a_2 + \dots + a_i\). Using a hash map to store the prefix sums, you can check if there is an index j such that \(S_i - S_j = k\), which indicates that the subarray from index j+1 to i sums to k.
Try to design an efficient solution that runs in linear time.
inputFormat
The input is given via standard input (stdin) and consists of two lines:
- The first line contains two space-separated integers:
n
(the number of elements in the array) andk
(the target sum). - The second line contains
n
space-separated integers representing the elements of the array.
outputFormat
Output a single line to standard output (stdout) with the string YES
if a contiguous subarray whose sum is equal to k
exists; otherwise output NO
.
5 15
1 2 3 4 5
YES