#K79232. Maximum Sum Subarray of Fixed Size
Maximum Sum Subarray of Fixed Size
Maximum Sum Subarray of Fixed Size
You are given an array of integers and two integers ( n ) and ( k ). The first integer ( n ) indicates the number of elements to consider from the array, and ( k ) is the size of the subarray. Your task is to find the contiguous subarray of size ( k ) with the maximum sum. If there are multiple subarrays with the same maximum sum, output the one that appears first.
For example, if ( n = 8 ), ( k = 3 ) and the array is (-2, 1, -3, 4, -1, 2, 1, -5, 4), then only the first 8 numbers (i.e. (-2, 1, -3, 4, -1, 2, 1, -5)) are considered. The subarray with maximum sum is ([4, -1, 2]) because (4 + (-1) + 2 = 5) is the highest sum among all contiguous subarrays of size 3.
The underlying idea to solve this problem is to use a sliding window technique. In each step, update the current window sum by subtracting the first element of the window and adding the next element in line. Keep track of the maximum window sum found so far and its starting index.
inputFormat
The input is read from standard input (stdin). It consists of two lines. The first line contains two space-separated integers ( n ) and ( k ), where ( n ) represents the number of integers to consider and ( k ) is the size of the subarray. The second line contains at least ( n ) space-separated integers. Only the first ( n ) integers should be used for processing.
outputFormat
Print to standard output (stdout) the contiguous subarray of size ( k ) with the maximum sum. The subarray should be printed as ( k ) space-separated integers on a single line.## sample
8 3
-2 1 -3 4 -1 2 1 -5 4
4 -1 2