#K49197. Find Sublist with Given Sum
Find Sublist with Given Sum
Find Sublist with Given Sum
You are given a list of N integers and three integers N, M, and S. Your task is to find the first occurrence of a contiguous sublist of length M that sums exactly to S. If such a sublist exists, output its starting index (0-indexed); otherwise, output -1.
This problem can be efficiently solved using a sliding window technique. Initially, compute the sum of the first M elements. Then, slide the window one element at a time by subtracting the element leaving the window and adding the new element entering the window. As soon as the sum equals S, output the starting index. If you complete the traversal without finding such a sublist, output -1.
Note: Input is provided through stdin
and output should be printed to stdout
.
inputFormat
The first line contains three integers N, M, and S separated by spaces, where:
- N is the number of elements in the array.
- M is the length of the sublist to consider.
- S is the target sum.
The second line contains N integers separated by spaces representing the array.
outputFormat
Print a single integer which is the starting index (0-indexed) of the first sublist of length M that adds up to S. If no such sublist exists, print -1.
## sample5 2 10
1 2 3 7 5
2