VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-minimum-sum-subarray-size-k/

⇱ Maximum sum of a subarray of size k - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum of a subarray of size k

Last Updated : 25 Aug, 2025

Given an array of integers arr[] and an integer k, find the maximum possible sum among all contiguous subarrays of size exactly k.
A subarray is a sequence of consecutive elements from the original array. Return the maximum sum that can be obtained from any such subarray of length k.

Examples:

Input  : arr[] = [100, 200, 300, 400],  k = 2
Output : 700
Explanation: We get maximum sum by adding subarray [300,400] of size 2

Input  : arr[] = [1, 4, 2, 10, 23, 3, 1, 0, 20], k = 4 
Output : 39
Explanation: We get maximum sum by adding subarray [4, 2, 10, 23] of size 4.

Input  : arr[] = [2, 3], k = 1
Output : 3
Explanation: The subarrays of size 1 are [2] and [3]. The maximum sum is 3.

[Naive Approach] Fixed-Size Window Brute Force - O(n × k) time and O(1) space

The idea is to iterate over all possible subarrays of size k and calculate their sums one by one. For each subarray, compare its sum with the current maximum and update accordingly.


Output
9

[Better Approach - 1] Using Prefix Sum - O(n) Time and O(n) Space

The idea is to precompute the prefix sum array where each element at index i stores the sum of elements from index 0 to i-1. Using this, we can compute the sum of any subarray in constant time O(1) using the difference of two prefix values. This eliminates the need to iterate over each subarray element repeatedly.


Output
9

[Better Approach - 2] Sliding Window using Queue - O(n) Time and O(k) Space

The idea is to use a queue to maintain a window of the last k elements as we iterate through the array. We keep track of the current window sum by adding the new element to the sum and removing the oldest element (from the front of the queue) once the size exceeds k. At each step where the window size is exactly k, we update the maximum sum encountered so far.
This ensures that we process each element exactly once and maintain the sliding window efficiently.


Output
9

[Expected Approach] Optimized Sliding Window - O(n) Time and O(1) Space

The idea is to use a sliding window of size k to efficiently compute the maximum sum of any subarray of size k.
First, calculate the sum of the initial window of size k.
Then, slide the window by one element at a time: subtract the element that goes out of the window and add the new element that comes in.

Step by Step Implementation:

  • Calculate the sum of the first k elements and store it as currSum.
  • Initialize maxSum = currSum.
  • For each index i from k to n - 1, update the window by doing currSum = currSum + arr[i] - arr[i - k].
  • This adds the new element arr[i] and removes the element that slid out arr[i - k].
  • Update maxSum = max(maxSum, currSum) after each step.
  • After the loop, return maxSum.

Output
9
Comment