#K45202. Maximum Sum of Contiguous Subarray of Fixed Size
Maximum Sum of Contiguous Subarray of Fixed Size
Maximum Sum of Contiguous Subarray of Fixed Size
Given an array of integers and an integer \(k\), find the maximum sum of any contiguous subarray of length \(k\). If \(k\) is greater than the number of elements in the array or if \(k\) equals 0, output 0.
You are required to employ an efficient algorithm – a sliding window approach is recommended. When sliding the window, the sum can be updated using the formula:
\(current\_sum = current\_sum + arr[i] - arr[i-k]\)
for \(i = k\) to \(n-1\), where \(n\) is the number of elements in the array.
inputFormat
Input is read from standard input. The first line contains two integers (n) and (k), where (n) is the number of elements and (k) is the size of the subarray. The second line contains (n) space-separated integers representing the array.
outputFormat
Output the maximum sum of any contiguous subarray of length (k). If no valid subarray exists, output 0.## sample
8 3
1 2 3 4 5 6 7 8
21