Back to ArraysMaximum Sum Subarray of Size K
Easy

Maximum Sum Subarray of Size K

EasyRecommendedSliding Window

Given an array and a fixed window size k, find the maximum sum among all contiguous subarrays of exactly length k.

Examples

Example 1

Input:
nums = [2,1,5,1,3,2], k = 3
Output:
9

Explanation: The window [5,1,3] (indices 2-4) sums to 9, the largest among all size-3 windows.

Example 2

Input:
nums = [4,2,1], k = 3
Output:
7

Explanation: When k equals the array's length, there is exactly one window — the whole array.

Example 3

Input:
nums = [3,-1,4], k = 1
Output:
4

Explanation: With k = 1, every 'window' is a single element, so the answer is simply the maximum element.

Constraints

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

Loading editor…

Code execution is coming soon.