Problem Statement
Given an integer array arr[] and an integer k, find the maximum sum of any contiguous subarray whose length is greater than or equal to k.
Example 1
Input
arr = [1, -2, 2, -3]
k = 3
Output
1
Explanation
Possible subarrays of length at least 3:
| Subarray | Sum |
|---|---|
| [1, -2, 2] | 1 |
| [-2, 2, -3] | -3 |
| [1, -2, 2, -3] | -2 |
Maximum sum = 1
Example 2
Input
arr = [1, 1, 1, 1, 1, 1]
k = 2
Output
6
The entire array has the maximum sum.
Understanding the Problem
If the question asked for the maximum subarray sum, we could directly use Kadane's Algorithm.
However, there is an additional condition:
The subarray length must be at least
k.
Therefore, Kadane's Algorithm alone cannot solve this problem.
Brute Force Approach
Generate every possible subarray having length ≥ k.
Calculate the sum.
Keep track of the maximum sum.
for every starting index
for every ending index
if length >= k
calculate sum
Complexity
Time Complexity
Brute Force: O(n³)
Using Prefix Sum: O(n²)
This is still not efficient because:
n = 100000
We need an O(n) solution.
Optimized Idea
We combine:
Kadane's Algorithm
Sliding Window
Step 1: Kadane's Algorithm
We create an array:
maxEndHere[]
where:
maxEndHere[i]
means:
Maximum subarray sum ending exactly at index
i.
Example
Suppose:
Index : 0 1 2 3 4
Value : 2 -3 4 5 -2
i = 0
maxEndHere[0] = 2
i = 1
Either take only:
-3
or extend the previous subarray:
2 + (-3) = -1
Maximum:
-1
maxEndHere[1] = -1
i = 2
Take only:
4
or extend:
-1 + 4 = 3
Maximum:
4
maxEndHere[2] = 4
i = 3
Take only:
5
or extend:
4 + 5 = 9
Maximum:
9
maxEndHere[3] = 9
i = 4
Take only:
-2
or extend:
9 - 2 = 7
Maximum:
7
Final array:
maxEndHere = [2, -1, 4, 9, 7]
Code
int[] maxEndHere = new int[n];
maxEndHere[0] = arr[0];
for (int i = 1; i < n; i++) {
maxEndHere[i] =
Math.max(arr[i],
maxEndHere[i - 1] + arr[i]);
}
Why Do We Need maxEndHere[]?
Suppose:
Window size = k
Current window:
[4, 5]
Window sum:
9
Before this window:
2, -3
There is a positive contribution:
2
So instead of considering only:
4 + 5
we may use:
2 - 3 + 4 + 5
or simply:
4 + 5
We need whichever is larger.
Kadane's Algorithm already tells us the best prefix ending before the window.
Step 2: Sliding Window
Maintain the sum of exactly k elements.
Example
1 2 3 4 5
k = 3
First window:
1 2 3
sum = 6
Move the window:
Remove:
1
Add:
4

Join the conversation! Your thoughts help the community grow.