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.

Example 1

Input
nums (int[]) = [2,1,5,1,3,2]
size (int) = 6
k (int) = 3
Returns (int) 9

Example 2

Input
nums (int[]) = [1,2]
size (int) = 2
k (int) = 3
Returns (int) 0

Example 3

Input
nums (int[]) = [-2,-1,-5]
size (int) = 3
k (int) = 2
Returns (int) -3

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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.