This is a classic sliding window problem

Problem Summary

You are given:

You must find:

Key Insight

Instead of recomputing sum every time:

We:

Idea

If window is:

[i ... i+k-1]

Then next window:

[i+1 ... i+k]

So update like:

newSum = oldSum + arr[i+k] - arr[i]

Algorithm

Step 1:

Compute sum of first k elements

Step 2:

Slide window till end:

Example

Input:

arr = [1, 4, 2, 10, 23, 3, 1, 0, 20], k = 4

Windows:

Output:

39

Java Solution

class Solution {
    public int maxSubarraySum(int[] arr, int k) {

        int n = arr.length;

        if (n < k) return -1;

        // first window sum
        int windowSum = 0;

        for (int i = 0; i < k; i++) {
            windowSum += arr[i];
        }

        int maxSum = windowSum;

        // slide window
        for (int i = k; i < n; i++) {

            windowSum += arr[i] - arr[i - k];

            maxSum = Math.max(maxSum, windowSum);
        }

        return maxSum;
    }
}

Complexity

Key Takeaways

Pattern Recognition

If you see:

Think:

Sliding Window Technique

Summary

This problem demonstrates the sliding window technique to efficiently compute the maximum sum of a fixed-size subarray. Instead of recalculating sums for each window, the approach updates the sum incrementally by adding the incoming element and removing the outgoing one, resulting in optimal time and constant space complexity. This pattern is widely used in interview problems involving contiguous subarrays.