#K66437. Maximum Sum Subarray of Fixed Size

    ID: 32420 Type: Default 1000ms 256MiB

Maximum Sum Subarray of Fixed Size

Maximum Sum Subarray of Fixed Size

You are given an array of n integers and an integer k. Your task is to compute the maximum sum of any contiguous subarray of length k. If k is not a valid subarray size (i.e., k ≤ 0 or k > n), output 0.

The problem can be formalized as follows:

Given an array \(A = [a_1, a_2, \ldots, a_n]\) and an integer \(k\), find \[ \max_{1 \leq i \leq n-k+1} \left(\sum_{j=0}^{k-1} a_{i+j} \right) \] if \(k > 0\) and \(n \geq k\); otherwise, output 0.

This is a typical sliding window problem that can be solved in \(O(n)\) time.

inputFormat

The input is given via standard input (stdin). 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 fixed subarray length. The second line contains n space-separated integers representing the array elements.

outputFormat

Output a single integer to standard output (stdout) representing the maximum sum of any contiguous subarray of length k. If k is invalid (i.e., k ≤ 0 or k > n), output 0.## sample

9 4
1 4 2 10 23 3 1 0 20
39