Maximum Sum Subarray of Size K

Implement maxSumSubarrayOfSizeK

Given an array of positive integers nums and an integer k, find the maximum sum of any contiguous subarray of size exactly k. Checking every window from scratch works, but it throws away the overlap between consecutive windows — a window sliding one step to the right shares k - 1 of its elements with the window before it. The sliding windowSliding WindowMaintaining a running result over a contiguous range that grows or shrinks one element at a time, instead of recomputing the result for every range from scratch. technique exploits that: keep a running sum and update it in O(1) per step by adding the element that just entered and removing the one that just left.

Example 1:

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

Output: 9

Example 2:

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

Output: 7

Example 3:

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

Output: 14

+ 10 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ nums.length

nums =

[2, 1, 5, 1, 3, 2]

k =

3