Intermediate Level
Implement the maximumSubarraySumFixedLength method that finds the maximum sum of any contiguous subarray of length k.
The input contains an integer array nums, its length size, and a window size k. Your task is to find the maximum sum of any contiguous subarray having exactly k elements.
If k is greater than size, return 0. For example, in [2,1,5,1,3,2] with k = 3, the best subarray is [5,1,3] and its sum is 9.
Use the sliding window technique to avoid recalculating every subarray sum from the beginning.
First calculate the sum of the first k elements. Then move the window one position at a time by adding the new right value and removing the old left value. Keep the largest window sum found.
Pseudocode:
function maximumSubarraySumFixedLength(nums, size, k):
if k > size:
return 0
windowSum = sum of first k elements
best = windowSum
for i from k to size - 1:
windowSum = windowSum + nums[i] - nums[i - k]
best = max(best, windowSum)
return best