🔗 Geeksforgeeks

Maximum Sum Subarray of Size K

Easysliding windowAmazonMicrosoftApple

Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k.


Return the maximum sum.

Examples

Input:nums = [2, 1, 5, 1, 3, 2], k = 3
Output:9
Explanation:Subarray [5, 1, 3] has the maximum sum of 9.
Input:nums = [2, 3, 4, 1, 5], k = 2
Output:7
Explanation:Subarray [3, 4] has the maximum sum of 7.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

💡 Hints

Hint 1

Calculate the sum of the first k elements. Then slide the window: add the new right element and subtract the old left element.

Hint 2

This avoids recalculating the entire window sum — just one addition and one subtraction per step.

Algorithm Complexity

Official asymptotic Big-O runtime and auxiliary memory analysis

Linear
Algorithmic Approach

Classic fixed-size sliding window. First calculate the sum of the initial window. Then slide right: add the new element entering the window, subtract the element leaving. Track the maximum sum.

Time ComplexityO(n)
Why:

Sliding window with two pointers advances right across array and shrinks left when window sum exceeds or matches target.

Space ComplexityO(1)
Why:

Maintains constant extra space with scalar pointers and a running sum variable.

Big-O Growth CurveLinear (O(N))
Execution time scales directly in proportion to the input size.

🌍 Real-World Use Cases

NetflixPeak viewership detection

Finding the 7-day window with the highest total viewership to plan marketing campaigns and content releases.

AmazonPeak order processing

Identifying the k-hour window with the highest order volume to optimize warehouse staffing.

🔍 Dry Run

Solution⏱ O(n) | 💾 O(1)
Line5
windowSum=8number
k=3number

First window [2,1,5]: sum = 2+1+5 = 8