Maximum Sum Subarray Size K Java | Fresher Interview
Fast recall
Quick revision
Core answer
Can you implement the classic fixed-size sliding window with correct boundary handling and clear incremental update logic
Using nested loops to recompute the sum for every window position, giving O(n^2) instead of incremental update
Use descriptive names like windowSum and maxSum, handle the initial window separately, and explain the slide operation
Interview-ready guide
Interview answer
To find the maximum sum subarray of size k, I'd use the sliding window technique.
First, I compute the sum of the first k elements to establish the initial window. That's my starting windowSum. I also set maxSum equal to that initial windowSum because the first window is a valid candidate.
Then I slide the window across the rest of the array. Starting from index k, for each position i, I update the windowSum by subtracting the element that's leaving the window, which is arr at i minus k, and adding the element that's entering, which is arr at i. After each update, I check if the new windowSum is greater than maxSum and update maxSum if it is.
By the time I reach the end of the array, maxSum holds the answer. This runs in O of n time because I touch each element exactly twice, once when it enters the window and once when it leaves. The space complexity is O of one because I only use a few variables.
The key mistake to avoid is using nested loops where you recompute the sum from scratch for every window. That's O of n squared. The whole point of sliding window is incremental update.
You're adjusting the previous sum, not recalculating it. This pattern works for any fixed-size window problem where you need a maximum, minimum, or average over exactly k consecutive elements.
For example, for [2, 1, 5, 1, 3, 2] with k = 3, the first window sums to 8. Sliding gives 7, then 9, then 6, so the maximum is 9 from [5, 1, 3].
Maximum Sum Subarray Size K Java | Fresher Interview
Direct Answer
Compute the sum of the first k elements to seed the window, then slide one step at a time — add the entering element and subtract the leaving one — tracking the maximum. This runs in O(n) time, O(1) space, far better than the O(n^2) nested-loop approach.
Deep Dive & Architecture
A fixed-size sliding window avoids summing the same elements repeatedly. Calculate the first k values once. Every move then adds the new right value and removes the old left value.
Worked example: [2, 1, 5, 1, 3, 2], k = 3
The first window [2, 1, 5] sums to 8. Slide right: subtract 2 and add 1, giving 7 for [1, 5, 1]. Next subtract 1 and add 3, giving 9 for [5, 1, 3]. The final window sums to 6, so the maximum is 9.
The invariant is that windowSum always equals exactly the k elements ending at the current right boundary. Initialize the maximum from the first window rather than zero; otherwise an all-negative input could incorrectly return zero.
Validate k: it normally must be positive and no larger than the array length. Decide whether invalid input throws an exception or returns a special result.
The initial sum costs O(k), and the remaining slides cost O(n - k), for O(n) total time and O(1) extra space. Recomputing every length-k range from scratch would cost O(nk). Use long if the sum of k integer values may overflow.
Code Example
public class MaxSumSubarray {
public static int findMaxSumSubarray(int[] arr, int k) {
if (arr == null || arr.length < k)
throw new IllegalArgumentException("Array too small for window size");
int windowSum = 0;
for (int i = 0; i < k; i++) windowSum += arr[i]; // initial window [0, k-1]
int maxSum = windowSum;
for (int i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k]; // slide: add right, drop left
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
public static void main(String[] args) {
int[] prices = {2, 1, 5, 1, 3, 2};
System.out.println(findMaxSumSubarray(prices, 3)); // 9 (subarray [5,1,3])
}
}
Common Mistakes & Pitfalls
- Nested loops recomputing the sum: looping start index then summing k elements is O(n^2). Slide and update the sum incrementally instead.
- Off-by-one in the slide loop: start the loop at
i = k(the first window ended atk-1); the update isarr[i] - arr[i-k]. - Forgetting to initialize maxSum: starting
maxSumat 0 breaks for all-negative arrays. Initialize it to the first window sum.
Check your understanding
Answer these without looking back at the article.
- What is the sliding window technique and when do you use it?
- How do you find the longest substring without repeating characters?
- How do you find all anagrams of a pattern in a string?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.