Data Structures and Algorithms (DSA)  

Max Sum Subarray of Size K

This is a classic sliding window problem

Problem Summary

You are given:

  • An array arr[]

  • A number k

You must find:

  • Maximum sum of any contiguous subarray of size k

Key Insight

Instead of recomputing sum every time:

  • Use Sliding Window

We:

  • Take first window sum

  • Slide window by 1 step:

    • Add new element

    • Remove old element

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:

  • update sum

  • track max

Example

Input:

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

Windows:

  • [1,4,2,10] = 17

  • [4,2,10,23] = 39

  • [2,10,23,3] = 38

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

  • Time Complexity: O(n)

  • Space Complexity: O(1)

Key Takeaways

  • Fixed size subarray → Sliding Window

  • Avoid recomputation using:

    • add incoming - remove outgoing

  • Very common interview pattern

Pattern Recognition

If you see:

  • “subarray of size k”

  • “maximum/minimum in window”

  • “contiguous segment”

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.