Introduction
The Maximum Sum Subarray of Size K problem involves finding the contiguous subarray of size k that has the largest sum.
Given an array arr[] of size n and an integer k, the task is to find the maximum sum among all possible subarrays of size k.
This problem is one of the most important beginner-level Sliding Window problems and helps in understanding window-based optimization techniques.
Example
Input: arr[] = [2, 1, 5, 1, 3, 2]k = 3 Output: 9 Explanation: Subarray [2, 1, 5] → Sum = 8 Subarray [1, 5, 1] → Sum = 7 Subarray [5, 1, 3] → Sum = 9 Subarray [1, 3, 2] → Sum = 6 Maximum Sum = 9
Input: arr[] = [4, 2, 1, 7, 8, 1] k = 2 Output: 15 Explanation: Subarray [4, 2] → Sum = 6 Subarray [2, 1] → Sum = 3
Subarray [1, 7] → Sum = 8
Subarray [7, 8] → Sum = 15
Subarray [8, 1] → Sum = 9
Maximum Sum = 15
Constraints
1 <= n <= 10^5
1 <= k <= n
-10^9 <= arr[i] <= 10^9
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Generate every possible subarray of size
k - Calculate the sum of each subarray
- Track the maximum sum
This approach is easy to understand but repeatedly calculating sums increases time complexity.
Steps
- Traverse the array from index 0 to n-k;
- For every starting index:
- calculate sum of next k elements
- Compare the sum with maximum sum.
- Return the final maximum sum.
Dry Run
Input Array: [2, 1, 5, 1, 3, 2]k = 3
Subarray [2, 1, 5]:
Sum = 8
Maximum Sum = 8
Subarray [1, 5, 1]:
Sum = 7
Maximum remains 8
Subarray [5, 1, 3]:
Sum = 9
Update Maximum Sum = 9
Subarray [1, 3, 2]:
Sum = 6
Maximum remains 9
Final Result: 9Brute Force Code
Complexity Analysis
Time Complexity: O(n * k)Explanation:
For every subarray, k elements are traversed again.
Space Complexity: O(1)
Explanation: No extra data structures are used.
Approach 2 : Optimized Solution (Sliding Window)
Explanation
Instead of recalculating the sum for every subarray, we can use the Sliding Window Technique.
The idea is:
- Calculate the first window sum
- Slide the window forward
- Add the new element entering the window
- Remove the old element leaving the window
This avoids repeated calculations and improves efficiency.
Steps
- Calculate sum of first
kelements. - Store it as current maximum sum.
- Slide the window one step at a time:
- subtract outgoing element
- add incoming element
- Update maximum sum whenever needed.
- Return maximum sum.
Input Array: [2, 1, 5, 1, 3, 2]
k = 3
First Window [2, 1, 5]:
Window Sum = 8
Maximum Sum = 8
Slide Window:
Remove 2
Add 1
New Window [1, 5, 1]
Window Sum = 7
Maximum remains 8
Slide Window Again:
Remove 1
Add 3
New Window [5, 1, 3]
Window Sum = 9
Update Maximum Sum = 9
Slide Window Again:
Remove 5
Add 2
New Window [1, 3, 2]
Window Sum = 6
Maximum remains 9
Final Result: 9Optimized Code