Function for calculating the maximum sum of a subarray with a length constraint
PHP
Hard
functions
Task «Function for calculating the maximum sum of a subarray with a length constraint»
Write a function `maxSubarraySum` that takes an array of integers (positive and negative) and an integer `k`. The function should return the maximum sum of any contiguous subarray whose length does not exceed `k`. If the array is empty or `k <= 0`, return `0`. Use a sliding window algorithm and dynamic programming for an efficient solution in O(n).
Input Format
The first line contains an integer n — the number of elements in the array. The second line contains n integers separated by spaces. The third line contains an integer k (1 <= k <= n).
Output Format
Integer — the maximum sum of a subarray of length at most k.
Examples
Example 1
INPUT
Привет мир
OUTPUT
0
Example 2
INPUT
Ааа Ббб
OUTPUT
0
main.php